Let's start writing our classes by declaring our instance variables and class headers for the Student class:
public class Student {
private int gradeLevel;
private String name;
private int age;
private Assignment assignment;
}
Now, we need to make our constructor for the Student class. The constructor will need to initialize all the above instance variables and allow the client to have the opportunity to set some of the variables to values of their own choosing. For this, we are allowing gradeLevel, name, and age to be set. These will be our constructor parameters with initial values.
An objectβs state refers to its attributes and their values at a given time; the state is defined by instance variables belonging to the object. Constructors are used to set the initial state of an object, which should include initial values for all instance variables.
We will first make the full constructor below and then write the overloaded constructors in Topic 5.9.
public class Student {
private int gradeLevel;
private String name;
private int age;
private Assignment assignment;
public Student(int gradeLev, String fullName, int ageNum) {
gradeLevel = gradeLev;
name = fullName;
age = ageNum;
assignment = null;
}
}
When a constructor is called, the parameters are local variables, which means that the variables are only defined inside that constructor. Notice how the parameter names are different than the names of the instance variables. In Topic 5.9 we will learn how to keep both as the same name which is the conventional way to do it.
If one of the parameters for the constructor is a mutable object (meaning that its state can be changed after it has already been created), the instance variable should be initialized with a copy of the object referenced in the parameter. This keeps us from accidentally changing the state of the original object.
Before we move on to the constructor for the Assignment class, if we don't include a constructor for a class, and we try to make a new object, Java will automatically create a default constructor with default values set for the instance variables. Here is a list of them for certain data types:
Data Type | Value |
Boolean | false |
Double | 0.0 |
Integer | 0 |
Objects/Reference Types | Null |
With that, let's do the same with the Assignment class.
public class Assignment {
private boolean correctAnswer;
public Assignment(boolean answer) {
correctAnswer = answer;
}
}
To see how constructors are used to create instances of a class, you can visit
Topic 2.2!