The “this” keyword refers to the current object in a method or constructor. In Java, this is a reference
variable that refers to the current object.
The most common use of this keyword is to eliminate the confusion between class attributes and parameters with the same name.
this keyword can also be used:
- to refer current class instance variable.
- to invoke current class method (implicitly)
- to invoke current class constructor.
- this can be passed as an argument in the method call.
- this can be passed as argument in the constructor call.
- this can be used to return the current class instance from the method.
Example:
public class Main {
int x;
public Main(int x) {
this.x = x;
}
// Call the constructor
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x);
}
}
0 comments:
Post a Comment