top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Variable Hiding and Variable Shadowing in Java

Introduction

Variable hiding and variable shadowing in Java are two concepts that might look synonymous, but they have some minute differences. The two terms are used in varied contexts, and here is a tutorial that explains the two. This tutorial also addresses variable hiding and variable shadowing in Java with examples for different kinds of variables.

Overview

Java helps us declare variables within any method, class, or block. Variable shadowing and variable hiding in Java occur if two variables have the same name but varied scopes. Here, the values in the lesser class or inner scope override or shadow the superclass or outer scope values.

What is shadowing in OOP?  

In Java, variables are defined within scopes, like a block, class, or method. When these defined variables have identical names to those defined in superclasses or outer scopes, the phenomenon is called shadowing. The phenomenon is called name masking when names are identical instead of variables.

Variable Hiding 

If you have defined a variable in the subclass with the same name defined in the superclass, it is called variable hiding in Java. In this case, the superclass variables remain hidden by the subclass variables.

Method Shadowing 

Method shadowing in Java is a phenomenon where methods are masked instead of variables. When you fill the same method in both subclass and superclass, including the parameters, the superclass method is shadowed by the subclass method. This mechanism is termed method shadowing.

Here’s an example demonstrating the concept:

class Superclass {
   public static void display() {
      System.out.println("This is the display method of the superclass");
   }
}
class Subclass extends Superclass {
   public static void display() {
      System.out.println("This is the display method of the subclass");
   }
}
public class MethodHiding {
   public static void main(String[] args) {
      MethodHiding obj = new MethodHiding();
      Subclass.display();
   }
}

Explanation:

Here in the given code, display () is the method name. It is described in both subclass and superclass, Subclass and Superclass, respectively. So, here if you use Subclass.display() command to call the display () method from the main (), the message thus printed will be “This is the display method of the subclass.”

Variable Hiding for Static Variables

When the various objects in a class share the same variable, it’s a static variable. Also, going by the term ‘class variable,’ you have to use the keyword ‘static’ to declare such a variable.

Here’s an example:

class Example {
  static int instanceCount = 0;
  public Example() {
    instanceCount++;
  }
  public static void main(String[] args) {
    Example obj1 = new Example();
    Example obj2 = new Example();
    Example obj3 = new Example();
    System.out.println("Number of instances created: " + Example.instanceCount);
    Example obj4 = new Example();
    Example obj5 = new Example();
    System.out.println("Number of instances created: " + Example.instanceCount);
  }
}
Here, instanceCount is the static variable created to keep a tab on total example object creation.
Now that you’re clear with what static variables are let’s understand static variable hiding in Java with the help of this example:
class Parent {
static String parentID = "1";
static String parentName = "ParentClass";
public void displayName() {
    System.out.println(parentName);
}
public void displayID() {
    System.out.println(parentID);
}
}
class Child extends Parent {
static int childID = 2;
static String childName = "ChildClass";
@Override
public void displayName() {
    System.out.println(childName);
}
@Override
public void displayID() {
    System.out.println(childID);
}
}
public class Main {
public static void main(String[] args) {
Parent parent = new Parent();
Child child = new Child();
    parent.displayID();
    parent.displayName();
    child.displayID();
    child.displayName();
} 

Explanation:

The given code has the Parent class with parentID and parentName static variables. The Child class, which adds two more static variables, namely childID, and childName, is an extension of the Parent class. The Child class, which is the subclass, thus overrides the variables defined in the superclass Parent class because both classes have exactly the same named variables.

Variable Hiding for Non-static Variables

Instance variables, also termed non-static variables, are related to instances of a class. Thus, each class object has its own set of instance variables. These variables store unique data and are open to access and modification.

Instance variable hiding in Java with example is given here for you to understand the concept better:

class Counter {
  int instanceCount = 0; // will get memory when instance is created
   Counter() {
    instanceCount++;
    System.out.println(instanceCount);
  }
  public static void main(String args[]) {
    Counter c1 = new Counter();
    Counter c2 = new Counter();
    Counter c3 = new Counter();
  }
}

Here instanceCount is the instance or the non-static variable. Now that you’re aware of what are non-static variables, here’s an example to understand variable hiding for non-static variables:

class Parent {
    String parentName = "ParentClass";
    public void displayName() {
        System.out.println(parentName);
    }
} 
class Child extends Parent {
    String childName = "ChildClass";
    @Override
    public void displayName() {
        System.out.println(childName);
    }
}
public class Main {
    public static void main(String[] args) {
        Parent parent = new Parent();
        Child child = new Child();
        parent.displayName();
        child.displayName();
    }
}

Explanation:

In the given code, parentName is defined under the Parent class. childName is a variable defined under the Child class, an extension of the superclass Parent class. Since the two variables have been defined with the same name, the Child class variable masks the Parent class variable. Thus, when the displayName() method is called in the subclass Child class, it prints the name of the child and not the parent.

Variable Hiding is Not the Same as Method Overriding 

Much like the difference between method overriding and method shadowing in Java, there is a slight difference between variable hiding and method overriding. Method overriding is a phenomenon in Java where the methods defined are the same in the child and parent classes. Thus, the child class here masks the method implementation of the parent class. 

Here’s an example for you to understand the differences better.

Variable hiding:

package com.kb.javainsimpleway.variable.hiding;
class Parent {
    int parentX = 10;
    static int parentY = 20;
}
class Child extends Parent {
    int childX = 100;
    static int childY = 200;
}
 public class VariableHidingInheritance {
    public static void main(String[] args) {
        Child child = new Child();
        System.out.println(child.childX);
        System.out.println(child.childY);
    }
}

Explanation:

In the given code are instance and static variables, namely parentX and parentY, respectively, in the Parent class. Child class, an extension of the Parent class, also has instance and static variables of similar names named childX and childY. Thus, here, the variables defined in the Child subclass demonstrate variable hiding, which masks the variables defined in the Parent superclass. 

Method overriding:

class Animal {
   public void displayInfo() {
      System.out.println("I am an animal.");
   }
}
class Dog extends Animal {
   @Override
   public void displayInfo() {
      System.out.println("I am a dog.");
   }
} 
class Main {
   public static void main(String[] args) {
      Dog dog1 = new Dog();
      dog1.displayInfo();
   }
}

Explanation:

In the given code, displayInfo() is a method under the Animal superclass that prints the statement ‘I am an animal.’ The extension of the Animal class is the Dog class, including the dog1 variable, which overrules the displayInfo() method. This subclass possesses an implementation that prints ‘I am a dog.’ Thus, on the object dog1, if you call the displayInfo() method, it will print ‘I am a dog.’

Access Shadowed Variable

Any instance variable is masked by the local variable in case they are defined with the same name. So, to access this shadowed variable, you have to use the keyword this. Here’s an example to make the concept clear:

class Student {
    // instance variable
    String studentName = "Tony Stark";
    public void print() {
        // local variable
        String name = "Steve Rogers";
        System.out.println(name); // prints local variable
        System.out.println(this.studentName); // prints instance variable
    }
}
public class Main {
    public static void main(String[] args) {
        Student student = new Student();
        student.print();
    }
}

Explanation:

In this code, the variable studentName is defined in the Student class. This class has the print() method, where there is a variable defined as a name incorporating the value “Steve Rogers.” While giving the print command, this keyword is used, which specifically refers to the variable defined under the Student class.

Access Hidden Variable 

If you have defined the subclass variable and superclass variable with the same name, the subclass variable will hide the superclass variable. So, if you want to access this superclass hidden variable, you must use the keyword super. If you’re wondering how to overcome instance variable hiding in Java, here’s an example to understand the concept:

class Parent {
    String parentName = "ParentClass";
     public void display() {
        System.out.println(parentName);
    }
}
class Child extends Parent {
    String childName = "ChildClass";
    @Override
    public void display() {
        System.out.println(childName);
        System.out.println(super.parentName);
    }
}
public class Main1 {
    public static void main(String[] args) {
        Child child = new Child();
        child.display();
    }
}

Explanation:

This code has a superclass named Parent, which the subclass Child extends. Inside the superclass, the variable is named as parentName, and within the subclass, the variable is defined as childName. The definitions being the same, the subclass variable hides the superclass variable. However, the keyword super is used here for accessing the variable parentName, specifically with the command super.parentName. 

Difference Between Variable Shadowing and Variable Hiding 

You might need clarification on the two look-alike terms. But here are the key differences between the two.

Variable shadowing is a same-class phenomenon. It takes place between variables defined in a similar class. However, variable hiding occurs between a child class and its parent class.

When you keep the local variable name and instance variable name the same within one class, variable shadowing occurs. However, it is termed variable hiding when instance variables in parent and child classes are the same. 

Conclusion

Being an effortless programming language, Java comes with a range of features. The simplicity of learning is first, followed by its platform independence. It is such a programming language that offers code reusability, and by learning it, you get one step closer to designing bug-free systems. It is also a robust programming language because of the sheer strength of its memory management and automated garbage collection. Thus, to kick-start your programming learning journey, Java can be the ideal first step.

FAQs

1. What is variable shadowing in JavaScript?

In JavaScript, variable shadowing means local and global variables have the same names. Thus the global variable gets overshadowed by the local variable.

2. How to access the hidden and shadowed variables?

You can access the hidden and shadowed variables using specific keywords. this keyword is used to specifically mention the shadowed variable, while the super keyword is used to mention the hidden variable explicitly.

3. Is variable shadowing bad?

No, variable shadowing isn’t bad in all cases. It helps prevent accidental mistakes. With variable shadowing, you can avoid errors like unintended re-assigning of variable values.

Leave a Reply

Your email address will not be published. Required fields are marked *