Variable Hiding in java, intro for this keyword

Java Programming Language / Class, Object and Methods in java

1384

Program:

 class VariableHiding {

 int variable = 5;

 void method(int variable) {
  variable = 20;
  System.out.println("Value of variable :" + variable);
  }

  void method() {
  int variable = 50;
  System.out.println("Value of variable :" + variable);
 }

 public static void main(String args[]) {
 VariableHiding obj = new VariableHiding();

 obj.method(20);
 obj.method();
 }
}

/*
this keyword can be very useful in the handling of Variable Hiding.
We can not create two instance/local variables with the same name.
However it is legal to create one instance variable & one local variable
or Method parameter with the same name. In this scenario the 
local variable will hide the instance variable this is called Variable Hiding.

*/

Output:

Value of variable :20
Value of variable :50
Press any key to continue . . .

Explanation:

As you can see in the example above the instance variable is hiding and the value of the local variable(or Method Parameter is displayed not instance variable. To solve this problem use this keyword with a field to point to the instance variable instead of the local variable.

This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.