Sunday, 14 January 2018

             The `this` keyword in java

The this keyword in java can be used for different purposes. Some of these are listed below.

(1) To refer to the current class instance variable. 

(2) To invoke current class method.

(3) The `this( )` method can be used to invoke the current constructor class.

(4) Can be used to return the current class instance from the method.

Now Consider the following example program given below.

/* Class Containing the main function */
class ThisKeyword
{
    public static void main (String args[])
    {
        /* Creating Object of the class Area */
        Area obj = new Area ();
        
        int area = 0;
        
        area = obj.getArea (50,100);
        
        System.out.println (area);
    }
}

class Area 
{
    int w = 10, h = 20;
    
    
    int getArea (int w, int h)
    {
        return (this.w * this.h);
    }
}




In the above program when we call the method `getArea ( ) ` along with the parameters 50 and 100 the values are passed to the getArea ( ) function in the class Area.

For computing and returning the area we use `this` keyword to refer to the values of `this` class (i.e. of class Area ( ). )

So the area returned will be (10 * 20 ) = 200.

The use of `this` keyword to invoke the current class method will be explained in the next post.


Keep Visiting.


             The `this` keyword in java The this keyword in java can be used for different purposes. Some of these are listed below. ...