instance variable hiding in Java

Java Programming Java 8Object Oriented Programming

A local variable of same name will hide the instance variable. In order to use the instance variable, we should use the this operator. See the example below −

Example

 Live Demo

public class Tester{
   int a = 1;

   public static void main(String[] args) {
      Tester t = new Tester();
      t.show();
      t.show1();
   }

   public void show(){
      int a = 2;
      System.out.println(a);
   }

   public void show1(){
      int a = 3;
      System.out.println(this.a);
   }
}

Output

2
1
raja
Published on 19-Sep-2018 08:30:36
Advertisements