this keyword, Variable Hiding in java

Java Programming Language / Class, Object and Methods in java

1925

Program:

 class VariableHiding {

int variable = 5;

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

  void method() {
  int variable = 50;
  System.out.println("Value of Instance variable :" + this.variable);
  System.out.println("Value of Local 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 Instance variable :5
Value of Local variable :20
Value of Instance variable :5
Value of Local variable :50
Press any key to continue . . .

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.