Thursday 13 December 2012

this Keyword

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

public class ThisDemo
{
    int a, b;
    ThisDemo(int a,int b)
    {
        this.a=a;   //a is local and this.a is global
        this.b=b;
    }
    public static void main(String[] args)
    {
        ThisDemo ob=new ThisDemo(10, 20);
        System.out.println(ob.a);
        System.out.println(ob.b);
       
    }
}




Output:
10
20
 


Another Example


public class ThisDemo
{
    int a, b;
    ThisDemo()
    {
        this(1,2);
    }
    public ThisDemo(int i, int j)
    {
        a=i;
        b=j;
    }
    public static void main(String[] args)
    {
        ThisDemo ob=new ThisDemo();
        System.out.println(ob.a);
        System.out.println(ob.b);
      
    }
}
 

Output:
1
2

No comments:

Post a Comment