The “this” keyword in Java is a reference to the current instance of the class in which it appears. It is primarily used to differentiate between instance variables or method parameters and class variables with the same name. Here are some key points about the “this” keyword:
Example:-
public class MyClass
{
private int value;
public void setValue(int value)
{
this.value = value; // “this” refers to the instance variable
}
}
Example:-
public class MyClass
{
private int value;
public MyClass()
{
this(0); // Calls the constructor with an int parameter
}
public MyClass(int value)
{
this.value = value;
}
}
Example:-
public class MyClass
{
private int value;
public MyClass setValue(int value)
{
this.value = value;
return this; // Returns the current object
}
}
Example:-
public class MyClass
{
private int value;
public void doSomething()
{
AnotherClass.anotherMethod(this); // Passes the current object to another method
}
}
Example:-
public class Outer
{
private int value;
class Inner
{
public void doSomething()
{
int value = 5;
System.out.println(value); // Local variable
System.out.println(this.value); // Inner class instance variable
System.out.println(Outer.this.value); // Outer class instance variable
}
}
}
The “this” keyword is a convenient way to work with the current object’s members and to clarify references when there is a variable name conflict. It’s a fundamental concept in Java object-oriented programming.