1 Aug 2012

this keyword in java with example


The keyword this is useful when you need to refer to instance of the class from its method. The keyword helps us to avoid name conflicts. As we can see in the program that we have declare the name of instance variable and local variables same. Now to avoid the confliction between them we use this keyword. Here, this section provides you an example with the complete code of the program for the illustration of how to what is this keyword and how to use it.

In the example, this.length and this.breadth refers to the instance variable length and breadth while length and breadth refers to the arguments passed in the method. We have made a program over this. After going through it you can better understand.

1. It points to current class object.
2. In order to differentiate between formal parameters and data members of the class when both variable names are same, data members of the class must be preceded by keyword this.

Here is the code of the program:

class test
{
    int a,b;
    disp(int a,int b)
    {
     this.a=a;
     this.b=b;
     System.out.print("a: "+a+"b: "+b);
     }
}

class demo
{
 public static void main(String arg[])
 {
  test t=new test();
  t.disp(10,20);
  }
}

0 comments:

Post a Comment