View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Variable Hiding and Variable Shadowing in Java: Key Differences with Examples

Updated on 24/04/20253,912 Views

Imagine you're in a school, and the class teacher and student share the same first name — “Aisha.” When someone says, “Aisha, come here,” it might get confusing unless it's clear whether they mean the student or the teacher. A similar situation can happen in Java when two variables with the same name exist in different scopes, and that’s where variable shadowing and variable hiding come into play.

These two terms sound alike but work differently. Shadowing happens when a local variable hides a class-level variable within the same class. Hiding, on the other hand, occurs when a child class hides a variable from its parent class. 

As you explore concepts like variable hiding and shadowing in Java, consider building a strong software development foundation. UpGrad’s Software Engineering Course covers core programming, system design, and much more.

Difference Between Variable Hiding and Variable Shadowing in Java: Variable Shadowing vs Variable Hiding in Java

Aspect

Variable Shadowing

Variable Hiding

Scope

Happens within the same class. A local variable hides an instance/class-level one.

Happens between parent and child classes. A child variable hides a parent variable.

Variable Type

Generally involves local vs instance variables.

Involves instance or static variables.

Access to Hidden Variable

Use this.variableName to access the shadowed instance variable.

Use super.variableName to access the hidden superclass variable.

Inheritance Involvement

No inheritance involved.

Inheritance is required (superclass and subclass).

Polymorphism Support

Not applicable. Shadowing does not involve polymorphism.

Not applicable. Hidden variables are not polymorphic.

Resolution Time

Resolved at compile-time.

Also resolved at compile-time.

Static Context

Does not apply to static variables.

Applies to both static and instance variables.

Common Use Case

When a method declares a variable that hides a class-level variable with the same name.

When a child class defines a variable already present in the parent class.

Example Scenario

Local name inside a method hides class-level name.

Child class’s name hides parent class’s name.

What Is Variable Shadowing in Java?

Variable shadowing occurs when a variable declared in an inner scope (such as a method or block) has the same name as a variable in the outer scope (such as a class field). In this case, the inner variable shadows or overrides access to the outer variable.

Example: Variable Shadowing

Scenario: A class Student has an instance variable name. Inside a method, a local variable with the same name is declared.

class Student {
    String name = "Tina Sharma"; // instance variable

    public void printName() {
        String name = "Satyam Rathore"; // local variable shadows instance variable
        System.out.println(name); // prints local variable
        System.out.println(this.name); // accesses shadowed instance variable
    }

    public static void main(String[] args) {
        Student student = new Student();
        student.printName();
    }
}

Output:

Satyam Rathore

Tina  Sharma

Explanation: The local variable name declared inside printName() shadows the instance variable. To access the original instance variable, we use this.name.

Want to take your Java skills to the next level? Explore the Professional Certificate Program in Cloud Computing and DevOps to build scalable and secure applications.

What Is Variable Hiding in Java?

Variable hiding occurs when a subclass declares a variable with the same name as a variable in its superclass. The subclass’s variable hides the one in the superclass.

Example: Variable Hiding (Instance Variables)

Scenario: A Child class extends a Parent class. Both define a variable name.

public class Main {
    public static void main(String[] args) {
        Child obj = new Child();
        obj.printNames();
    }
}

class Parent {
    String name = "ParentClass";
}

class Child extends Parent {
    String name = "ChildClass"; // hides Parent's 'name'

    void printNames() {
        System.out.println("Child name: " + name);        // accesses Child's 'name'
        System.out.println("Parent name: " + super.name); // accesses Parent's 'name'
    }
}

Output:

Child name: ChildClass

Parent name: ParentClass

Explanation:

This code demonstrates variable hiding in Java, where the Child class defines a variable name that hides the same variable from the Parent class. Using super.name, the child can still access the hidden parent variable.

Static Variable Hiding

When a static variable with the same name is declared in a subclass, it hides the static variable in the superclass.

Example:

Both Parent and Child classes define a static variable id.

public class Main {
    public static void main(String[] args) {
        System.out.println("Child.id: " + Child.id);     // prints Child's static id
        System.out.println("Parent.id: " + Parent.id);   // prints Parent's static id
    }
}

class Parent {
    static String id = "1";
}

class Child extends Parent {
    static String id = "2"; // hides Parent's static 'id'
}

Output:

Child.id: 2

Parent.id: 1

Explanation:

This example shows static variable hiding, where Child defines a static variable id that hides the id in Parent. Accessing Child.id and Parent.id directly shows how each class maintains its own version of the static variable.

While we're discussing hiding, let's clarify the difference between method hiding and overriding.

Method Hiding vs Method Overriding

Method Hiding (Static Methods)

Scenario: Both parent and child classes define a static method display().

When a subclass defines a static method with the same signature as in the parent class, the superclass method is hidden.

public class Main {
    public static void main(String[] args) {
        Subclass.display();       // Calls Subclass's static method
        Superclass.display();     // Calls Superclass's static method
    }
}

class Superclass {
    public static void display() {
        System.out.println("Superclass method");
    }
}

class Subclass extends Superclass {
    public static void display() {
        System.out.println("Subclass method");
    }
}

Output:

Subclass method  

Superclass method

Explanation:

This example demonstrates method hiding in Java, where both Superclass and Subclass define a static method with the same signature. Static methods are resolved at compile-time, so the method call is determined by the class name used, not the object type.

Also read: Overloading vs Overriding in Java

Method Overriding (Instance Methods)

Scenario: A Dog class overrides the sound() method from the Animal class.

public class Main {
    public static void main(String[] args) {
        Animal a = new Dog(); // Create a reference of type Animal pointing to Dog
        a.sound(); // Calls Dog's overridden sound method and prints "Bark"
    }
}

class Animal {
    public void sound() {
        System.out.println("Generic sound");
    }
}

class Dog extends Animal {
    @Override
    public void sound() {
        System.out.println("Bark");
    }
}

Output: Bark

Explanation:

This code demonstrates method overriding, where the Dog class overrides the sound() method from the Animal class. When the method sound() is called on an Animal reference that points to a Dog object, the overridden method in Dog is invoked, printing "Bark."

Best Practices to Avoid Variable Hiding and Variable Shadowing in Java

  • Avoid reusing variable names in different scopes.
  • Use meaningful, distinct variable names.
  • Use this and super for clarity.
  • Enable compiler warnings for variable name conflicts.

Conclusion

Variable shadowing and hiding are subtle yet important concepts in Java's object-oriented model. Understanding their differences is crucial for writing clean, bug-free, and maintainable code. While shadowing occurs in the same class and affects scope resolution, hiding deals with inheritance and class hierarchies. Java does not allow overriding of variables, only hiding. So, pay attention to naming conventions and leverage this or super for clarity.

Java’s well-structured object model ensures you can manage complexity effectively — and understanding these nuances is one more step toward mastering it.

FAQs

1. What is variable shadowing in Java with an example?

Variable shadowing happens when a local variable (declared inside a method or block) has the same name as a class-level (instance) variable. The local variable takes precedence. For example, inside a method, declaring int age = 20; will shadow the class’s int age variable temporarily.

2. What is variable hiding in Java with an example?

Variable hiding occurs when a subclass declares a variable with the same name as a variable in its superclass. The subclass variable hides the superclass variable. Use super.variableName to access the hidden parent variable in this case, especially in inheritance scenarios.

3.  Can shadowed or hidden variables be accessed in Java?

Yes. Shadowed instance variables can be accessed using the this keyword, while hidden superclass variables can be accessed using the super keyword. This is helpful when you want to reference the outer or parent variable explicitly despite name duplication.

4. Can static variables be shadowed or hidden?

Static variables can be hidden, but not shadowed. Shadowing happens only with instance or local variables within the same class. Static variable hiding occurs between parent and child classes when both declare static variables with the same name.

5. Does Java allow overriding of variables like it does for methods?

No. Variables in Java are not polymorphic and cannot be overridden. They can only be hidden, meaning the variable in the subclass with the same name hides the one in the parent class. This contrasts with methods, which can be overridden.

6. Is method shadowing a valid concept in Java?

No. The correct terms are method hiding (for static methods) and method overriding (for instance methods). There is no concept of "method shadowing" in Java. It only applies to variables and specifically to local vs. instance variable conflicts.

7. How does Java resolve variable shadowing and hiding?

Both variable shadowing and hiding are resolved at compile-time. Java uses the reference type and scope to determine which variable to access. This differs from method overriding, which is resolved at runtime via dynamic binding.

8. Can shadowing/hiding lead to runtime errors in Java?

No. Shadowing and hiding themselves do not cause runtime errors. However, they can lead to confusing code and logic bugs if variable names are reused improperly. It’s best to use distinct variable names to improve code readability and avoid ambiguity.

9. How to avoid variable shadowing and hiding in Java?

Use meaningful and distinct variable names in different scopes and avoid reusing names unnecessarily. Also, use this and super for clarity when referencing class or superclass variables, and enable compiler warnings for variable conflicts.

10. Does variable hiding affect method resolution?

No. Variable hiding has no effect on method resolution or overriding. Variables and methods in Java are treated differently. Even if a subclass hides a variable, method calls are still dynamically bound and determined by the actual object’s class at runtime.

11.  Is variable hiding a good practice in Java?

Generally, no. While Java allows it, hiding variables can make code harder to understand and maintain, especially in complex class hierarchies. It’s better to avoid reusing variable names across parent-child classes unless you have a specific reason to do so.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.