Saturday 2 March 2013

this keyword in java


this keyword: Java define “this” keyword, that can be used inside any method to refer the current object.  “this” is always a reference to the object on which method was invoked.  “this” reference is implicitly used to refer to both the instance variables and methods of current object.

Example 1:

class Box
{
            int len,dep,hei;
            Box(int len,int dep, int hei)
            {
            this.len=len;
            this.dep=dep;
            this.hei=hei;
            }
            int volume()
            {
            return len*dep*hei;
            }
}
class this1
{
            public static void main(String[] args)
            {
                        Box obj=new Box(1,2,3);
                        int x=obj.volume();
                        System.out.println("volume="+x);
            }
}

O/P:    volume=6

            “this” reference is also used explicitly refer to the instance variables.

Example 2:

class Box
{
            int len=10;
            void method()
            {
            int len=40;
            System.out.println("local value="+len);
            System.out.println("Instance value="+this.len);
            }
}
class this2
{
            public static void main(String[] args)
            {
                        Box obj=new Box();
                        obj.method();
            }
}

O/P:    local value=40
            Instance value=10

1 comment: