Instance Variable Hiding and use of "this" keyword || use of This keyword in java || How to use This keyword in java || What is the use of This keyword in java?

 Instance Variable Hiding and use of "this" keyword:

"This" keyword

When a local variable has the same name as an instance variable, the local variable hides the instance variable. this is always a reference to the object on which the method was invoked. Because this lets you refer directly to the object, you can use it to resolve any name space collisions that might occur between instance variables and local variables.

Example:

class Rectangle
{
int height, width;
Rectangle(int height,int width)
{ //this used here
this.height = height;
this.width = width;
}
void showRect()
{
System.out.println("Height = " + height + "\nWidth = " + width);
}
public static void main(String args[])
{
Rectangle myRec = new Rectangle(3,4);
myRec.showRect();
}
}

OUTPUT
Height = 3
Width = 4


Example without "this" keyword
class Rectangle
{
int height, width;
Rectangle(int height,int width)
{ //Here is error
height = height;
width = width;
}
void showRect()
{
System.out.println("Height = " + height + "\nWidth = " + width);
}
public static void main(String args[])
{
Rectangle myRec = new Rectangle(3,4);
myRec.showRect();
}
}

OUTPUT:
Height = 0
Width = 0

Post a Comment

Please do not enter any spam link in the comment box