Tuesday, 20 December 2011

07 - this keyword

//Demonstrating the use of "this" keyword.

/*
    When the parameter names in a method are equal the names of the instance variables,
    the paramters will hide the instance variables. This concept is known as instance
    variables hiding.

    Lets see the following piece of code:

    class Box
    {
        int length;
        int width;
        int height;
   
        Box(int length,int width,int height)
        {
            length = length;
            width = width;
            height = height;
        }
    }

    If you look at the Box constructor above, the names of the three parameters and the
    names of the instance variables are same. So, this is an ambiguous situation.

    To eliminate this kind of situation we use the "this" keyword.
    "this" always refers to the current object.

    Lets see how to elimiate the ambiguity in the above piece of code...
*/

class Box
{
    int length;
    int width;
    int height;

    Box(int length,int width,int height)
    {
        this.length = length;
        this.width = width;
        this.height = height;
    }

    void volume()
    {
        System.out.println("Volume of the Box is: "+(length*width*height));
    }
}

class BoxDemo
{
    public static void main(String args[])
    {
        Box b1 = new Box(10,20,30);
        b1.volume();
    }
}

//Remove all the "this" keywords in the above program and observe the output.

Download the program only: http://paste2.org/followup/1832519

No comments:

Post a Comment