1. Keyword 'this' in Java is a reference variable that refers to the current object.
2. It can be used to refer current class instance variable
3. It can be used to invoke or initiate current class constructor
4. It can be passed as an argument in the method call
5. It can be passed as argument in the constructor call
6. It can be used to return the current class instance
7. "this" is a reference to the current object, whose method is being called upon.
8. You can use "this" keyword to avoid naming conflicts in the method/constructor of your instance/object.
Example-1: Using ‘this’ keyword to refer current class instance variables
class Test
{
int a;
int b;
Test(int a, int b) // Parameterized constructor
{
this.a = a;
this.b = b;
}
void display()
{
System.out.println("a = " + a + " b = " + b);
}
public static void main(String[] args)
{
Test object = new Test(10, 20);
object.display();
}
}
Example 2: Using ‘this’ keyword to invoke current class method
class Test {
void display()
{
// calling fuction show()
this.show();
System.out.println("Inside display function");
}
void show() {
System.out.println("Inside show funcion");
}
public static void main(String args[]) {
Test t1 = new Test();
t1.display();
}
}
0 Comments