This, super, and constructors
The keyword this
provides a reference to the current object. The keyword super
refers to the parent class object. A constructor is used to initialize the object state (values of the instance fields). It can be accessed using the keywords new
, this
, or super
.
Keyword this and its usage
We saw several examples of its usage in a constructor similar to the following:
public SimpleMath(int i) { this.i = i; }
It allows us to clearly distinguish between the object property and local variable, especially when they have the same name.
Another use of the keyword this
can be demonstrated in the implementation of the method equals()
in the following Person
class:
public class Person { private String firstName; private String lastName; private LocalDate dob; public Person(String firstName, String lastName, LocalDate dob) { this.firstName = firstName; this.lastName = lastName; this.dob = dob; } public String getFirstName() { return firstName; } public String getLastName...