Home » java » this keyword in java

this keyword in java

Local Variable Hides Instance Variable

In java when the local variable has the same name as an instance variable, the local variable hides the instance variable.

Result

In above program we have two instance variable with value a=10 and b=10. in method display there is a local variable a with value 5.

Inside method display() local variable a hides the instance variable a and it prints local variable’s value that is 5.

To resolve this problem we use this keyword

this keyword

“this” keyword can be used inside any method to refer to current object.     

In Java, we can’t declare two local variables with the same name within the same scope.

When the local variable has Java same name as an instance variable, the local variable hides the instance variable.                                                                                                                                                          “this” keyword solve the namespace collision that might occur between instance variable and local variable.

above problem can solve as given here

Result

Les see another example where we pass parameter to constructor and assign that value to instance variable

Result

Please follow and like us:
error