this Keyword

PREVIOUS

this keyword
this keyword refers to the object that is currently executing. It is useful for a method to reference instance variables relative to the this keyword.

Syntax of using this keyword

this.varName

varName is a name of an instance variable.

Another use of the this keyword is it allows one constructor to explicitly invoke another constructor in the same class.

Syntax to call another constructor of same class using this keyword  

this(args);

Examples of this keyword

Example 1 : Program that creates class Square and assigns values to variables using constructor and this keyword

class Square
{
       int height;
       int width;

         Square(int height, int width)
         {
               // Note that constructor variable and instance variable names are same
               
                this.height = height
                this.width = width;
          }
}

class ImplSquare
{
     public static void main(String args[])
     {
             Square sObj1 = new Square(2,3);             

             System.out.println("Variable values of object : ");
             System.out.println("Object height =  " + sObj1.height);
             System.out.println("Object width = " + sObj1.width);
      }
}


Output

Variable values of object : 
Object height =  0
Object width =  0

No comments:

Post a Comment