Using the this Keyword in Java
1. Reference to the Current Object
Sometimes a method needs to refer to the object that invoked it. The this keyword in Java is used within the body of any instance method or constructor to refer to the current object.
Consider a constructor where the parameters have the same names as the class variables. In this case, the parameters "shadow" the scope of the class variables, making it impossible to refer to the class variables directly. To resolve this, the this keyword is used:
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
} In this example, using the this keyword is necessary to distinguish the class fields from the local parameters. However, if the names were different, it would not be strictly required:
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
} 2. Using this() in a Constructor
The second way to use the this() keyword is to call one constructor from another within the same class. This is known as constructor chaining. A this() call must always be the very first line of the constructor:
public class Toy {
String name;
int cost;
String manufacturer;
int age;
```
public Toy(String name, int cost, String manufacturer, int age) {
this(name, cost, manufacturer);
this.age = age;
System.out.println("In the constructor with four parameters");
}
public Toy(String name, int cost, String manufacturer) {
this();
this.name = name;
this.cost = cost;
this.manufacturer = manufacturer;
System.out.println("In the constructor with three parameters");
}
public Toy() {
System.out.println("In the default constructor");
}
```
} public class ToyExample {
public static void main(String[] args) {
Toy toy = new Toy("Doll", 34, "Disney", 3);
}
}
Program output:
In the default constructor
In the constructor with three parameters
In the constructor with four parameters
Please log in or register to have a possibility to add comment.