Use of ‘this’ reference in Java

Today we will discuss the heavily used keyword 'this' in Java.

Following are the ways to use ‘this’ keyword in java :

1. Using ‘this’ keyword to refer current class instance variables.
class Shimpu
{
    int a;
    int b;
     
    // Parameterized constructor
    Shimpu(int a, int b)
    {
        this.a = a;
        this.b = b;
    }
    void display()
    {
        //Displaying value of variables a and b
        System.out.println("a = " + a + "  b = " + b);
    }
    public static void main(String[] args)
    {
        Shimpu object = new Shimpu(10, 20);
        object.display();
    }
}

output : a = 10 b = 20
2. Using this() to invoke current class constructor.
// Java code for using this() to 
// invoke current class constructor
class Shimpu
{
    int a;
    int b;
    //Default constructor
    Shimpu()
    {  
        this(10, 20);
        System.out.println("Inside  default constructor \n");
    }
     
    //Parameterized constructor
    Shimpu(int a, int b)
    {
        this.a = a;
        this.b = b;
        System.out.println("Inside parameterized constructor");
    }
    public static void main(String[] args)
    {
        Shimpu object = new Shimpu();
    }

}

output : 
Inside parameterized constructor
Inside  default constructor
3. Using ‘this’ keyword to return the current class instance.
//Java code for using 'this' keyword 
//to return the current class instance
class Shimpu
{
    int a;
    int b;
    //Default constructor
    Shimpu()
    {
        a = 10;
        b = 20;
    }
     
    //Method that returns current class instance
    Shimpu get()
    {
        return this;
    }
     
    //Displaying value of variables a and b
    void display()
    {
        System.out.println("a = " + a + "  b = " + b);
    }
    public static void main(String[] args)
    {
        Shimpu object = new Shimpu();
        object.get().display();
    }
}

output : a = 10 b = 20
4. Using ‘this’ keyword as method parameter
// Java code for using 'this' 
// keyword as method parameter
class Shimpu
{
    int a;
    int b;
     
    //Default constructor
    Shimpu()
    {
        a = 10;
        b = 20;
    }
     
    //Method that receives 'this' keyword as parameter
    void display(Test obj)
    {
        System.out.println("a = " + a + "  b = " + b);
    }
  
    //Method that returns current class instance
    void get()
    {
        display(this);
    }
    public static void main(String[] args)
    {
        Shimpu object = new Shimpu();
        object.get();
    }
}

output : a = 10 b = 20
Hope you like it. Please comment for any doubts
Happy Learning !!!
SHARE

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment