Problem 225
Constructors
It is time we start to complicate the creation of classes.
Think about creating an instance of an object. And then assigning values to its fields.
Student student = new Student();
student.firstName = "Frank";
student.lastName = "Smith";
student.birthYear = 1988;
Wouldn’t it be nice to include all that on one line?
You can.
All you need is a constructor as part of your class to be able to take the specific data and automatically assign the data to the object’s fields.
Constructors
It is proper form to always include a constructor when creating a class. Essentially, a constructor is just a method that takes arguments and assigns them to the object’s fields.
For ourStudent
class, the constructor would look like this:
class Student {
.
.
.
public Student(String firstName, String lastName, int birthYear) {
this.firstName = firstName;
this.lastName = lastName;
this.birthYear = birthYear;
}
.
.
.
}
The this
keyword comes in handy to differentiate between the parameter variable and the
current (this
) objects field name.
Now, when we create an instance of a Student
, we can assign the relevant info when it is created.
Student student = new Student("Frank", "Smith", 1988);
Just like any other method, it is important we know the order of the required parameters.
◄ 175: Sorting Records on Two Fields 226: Dog Constructor ►