Combining variables and methods
Classes define a classification of objects that share characteristics.
Characteristics can be data and code.
Also known as variables and methods.
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public boolean canVote() {
return age >= 18;
}
}
Objects are instances of classes.
Each object has its own set of instance variables.
In this case, each student has their own name and age.
private String name;
private int age;
Just like other variables we’ve used but defined at the top-level of a class rather than inside a method.
Can have a access modifier before the type.
Instance variables are usually private
.
public Student(String name, int age) {
this.name = name;
this.age = age;
}
Like a method but no return type.
And name is the same as the class name.
Its job is to initialize the object.
public boolean canVote() {
return age >= 18;
}
public boolean alphabeticallyBefore(Student other) {
return name.compareTo(other.name) < 0;
}
Non-static methods can refer to the instance variables of the object by just their name.
Methods can also take other arguments.
Can also access instance variables of other object if they are accessible.
Objects are constructed by calling the constructor with the
keyword new
.
Student fred = new Student("Fred", 17);
Student wilma = new Student("Wilma", 16);
Student barney = new Student("Barney", 18);
fred.canVote() ⟹ false
wilma.canVote() ⟹ false
barney.canVote() ⟹ true
fred.alphabeticallyBefore(wilma) ⟹ true
Note that the canVote
method doesn’t take any
arguments.
But the behavior of the method is affected by the data hidden in the object.
To use an object you need to know what methods it supports.
Methods are defined by their method signature: the name, the return type, and the types of the arguments.
If you are going to create new instances of a class you need to know what constructors it has and what arguments they take.