To unhide non-static fields from local fields.
Example:
double height; // "height" field
void setHeight(double height) { // "height" parameter
height = height; // ???
}
this.height = height;
resolves the ambiguity)For constructor chaining.
To access the instance of an outer object.
In Java, local variables must be initialized before use; otherwise, it raises a compiler error.
Example:
int a;
a++; // compiler error
Human obj;
obj.walk(); // compiler error
In Java, a reference can be initialized to null (if no specific object is available yet), but it must be initialized to an appropriate object before use, or it will raise a NullPointerException
at runtime.
Example:
Human h = null; // reference initialized to null
h = new Human(); // reference initialized to the object
h.walk(); // invoke the method on the object
Example:
Human h = null;
h.walk(); // NullPointerException
Constructor chaining is executing a constructor of the class from another constructor (of the same class).
Example:
Human(int age, double height, double weight) {
this.age = age;
this.height = height;
this.weight = weight;
}
Human() {
this(0, 1.6, 3.3);
//...
}
Constructor chaining (if done) must be on the very first line of the constructor.