Using this operator in Java

this is always a reference to the object on which the method was invoked. Consider this example

class ex1
{
    int x=1,y=1;
    public ex1(int x,int y)
    {
        this.x=x; //this.x refers to the class variable x not to the location function variable
        this.y=y; //for your better understanding in this place this operator can be considered as (this == e)
    }
    public void dis()
    {
        System.out.println("X: "+x+" Y: "+y+this.getClass().getName()); //getClass().getName() returns the object class name
    }
    public static void main(String args[])
    {
        ex1 e = new ex1(10,5);
        e.dis();
        ex2 e1 = new ex2();
    }
}
class ex2
{
    ex2()
    {
        System.out.println(this.getClass().getName());
    }
}

In this above program this operator is used to get the name of the current objects class. this operator cannot be used inside the static method. this operator can also be used to call other methods in the class.

OUTPUT:

X: 10 Y: 5ex1
ex2
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s