Overview
In this tutorial, we will learn about this keyword in Java. When used in the instance method or constructor this points to or references the current object. Method or constructor arguments can shadow the object variables with the same names. We use this to refer the object variables.
Example
package staff; // www.TestingDocs.com - Java Tutorials public class Staff { private String name; private String address; //Staff no-arg constructor public Staff() { } //Staff class constructor public Staff(String name, String address) { this.name = name; this.address = address; } }
In the Staff class constructor the arguments shadow the instance variables. We use this keyword to reference the object fields.
Calling overloaded constructors
Another most common use of this keyword is to invoke constructor from another. We can call another constructor of the class using this keyword.
//Staff constructor public Staff(String name) { this.name= name; } //Staff class constructor public Staff(String name, String address) { this(name); this.address = address; }
Notice that we have invoked the constructor:
this(name);
Note that the constructor call should be the first statement in the constructor. The below code is INVALID
//Staff class constructor public Staff(String name, String address) { this.address = address; this(name); }
—
Java Tutorial on this website:
https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :