Java this Keyword
The this keyword in Java refers to the current object. Any member of the current object can be referred to by using the this keyword from within a constructor or an instance method.
The this keyword can only be used within a constructor and an instance method.
Example
public class Student {
private String fullName;
private String email;
/* this keyword within a constructor */
public Student(String fullName, String email) {
this.fullName = fullName;
this.email = email;
}
/* this keyword within an instance method */
public void setStudent(String fullName, String email) {
this.fullName = fullName;
this.email = email;
}
}
The this keyword is usually used to refer to the member of the current object.
Uses of the this keyword
- The this keyword can be used to invoke the constructor of the current Class.
- The this keyword can be used to assign value to the field of the current Class.
- The this keyword can be used to invoke the method of the current Class
- The this keyword can be used to pass argument in the constructor call.
- The this keyword can be used to pass argument in the method call
- The this keyword can be used to return the object of the current Class.
Explicit Constructor Invocation
The this keyword can be used to call another constructor from within a constructor of the same class.
The invoking of a constructor from within different constructor of the same class is called explicit constructor invocation.
Example
Here is an example of a Square class that contains three constructors. Each constructor initializes the values of some or all of the Square's fields:
public class Square {
private double height;
private double width;
private int x;
private int y;
public Square() {
this(2, 2, 0, 0);
}
public Square(double height, double width) {
this(height, width, 0, 0);
}
public Square(double height, double width, int x, int y) {
this.height = height;
this.width = width;
this.x = x;
this.y = y;
}
}
If an object of the above Square class is created using no-argument constructor, the class member variables are assigned default values, height is assigned 2, width is assigned 2, x is assigned 0, and y is assigned 0. Similarly, if an object is created using the second constructor, height and width can be assigned a custom value, while x and y are given default values of 0.