What is variable shadowing in java?

Java 8Object Oriented ProgrammingProgramming

In Java you can declare three types of variables namely, instance variables, static variables and, local variables.

  • Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
  • Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
  • Class (static) variables − Class variables are variables declared within a class, outside any method, with the static keyword.

Variable Shadowing

If the instance variable and local variable have same name whenever you print (access) it in the method. The value of the local variable will be printed (shadowing the instance variable).

Example

In the following Java example, the class FieldShadowingExample has two instance variables (name, age) and a method (display()).

In the method there are two variables same as the instance variables (name and type).

When you invoke print (access) them in the method, the local variable values will be printed shadowing the instance ones.

 Live Demo

public class FieldShadowingExample{
   String name = "Krishna";
   int age = 25;
   public void display(){
      String name = "Vishnu";
      int age = 22;
      System.out.println("Name: "+name);
      System.out.println("age: "+age);
   }
   public static void main(String args[]){
      new FieldShadowingExample().display();
   }
}

Output

Name: Vishnu
age: 22

If you still, need to access the values of instance variables in a method (in this case) you need to access them using this keyword (or object) as shown below −

Example

 Live Demo

public class FieldShadowingExample{
   String name = "Krishna";
   int age = 25;
   public void display(){
      String name = "Vishnu";
      int age = 22;
      System.out.println("Name: "+name);
      System.out.println("age: "+age);
      System.out.println("Name: "+this.name);
      System.out.println("age: "+this.age);
   }
   public static void main(String args[]){
      new FieldShadowingExample().display();
   }
}

Output

Name: Vishnu
age: 22
Name: Krishna
age: 25
raja
Published on 05-Jul-2019 13:53:08
Advertisements