Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Variable Shadowing and Hiding in Java

DZone's Guide to

Variable Shadowing and Hiding in Java

Let's take a look at the fundamental practices of variable shadowing and hiding in Java, they work, and some advice on how best to use them.

· Java Zone ·
Free Resource

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Java allows us to declare a variable whenever we need it. We can categorize all our variables into three categories, which have different-different scopes:

  1. Instance variables: defined inside a class and have object-level scope.
  2. Class variables: defined inside a class with the static keyword. They have class-level scope common to all objects of the same class.
  3. Local variables: defined inside a method or in any conditional block. They have block-level scope and are only accessible in the block where they are defined.

what-is-variable-hiding-shadowing

What Is Variable Shadowing?

Variable shadowing happens when we define a variable in a closure scope with a variable name that is the same as one for a variable we've already defined in an outer scope.

In other words, when a local variable has the same name as one of the instance variables, the local variable shadows the instance variable inside the method block.

In the following example, there is an instance variable named x, and inside method printLocalVariable(), we are shadowing it with the local variable x.

class Parent {

    // Declaring instance variable with name `x`
    String x = "Parent`s Instance Variable";

    public void printInstanceVariable() {
        System.out.println(x);
    }

    public void printLocalVariable() {
        // Shadowing instance variable `x` with a local variable with the same name
        String x = "Local Variable";
        System.out.println(x);

        // If we still want to access the instance variable, we do that by using `this.x`
        System.out.println(this.x);
    }
}


What Is variable Hiding?

Variable hiding happens when we define a variable in a child class with the same name as one we defined in the parent class. A child class can declare a variable with the same name as an inherited variable from its parent class, thus hiding the inherited variable.

In other words, when the child and parent classes both have a variable with the same name, the child class' variable hides the parent class' variable.

In the following example, we are hiding the variable named x in the child class while it is already defined by its parent class.

class Child extends Parent {

    // Hiding the Parent class's variable `x` by defining a variable in the child class with the same name.
    String x = "Child`s Instance Variable";

    @Override
    public void printInstanceVariable() {
        System.out.print(x);

        // If we still want to access the variable from the super class, we do that by using `super.x`
        System.out.print(", " + super.x + "\n");
    }
}


Variable Hiding Is Not the Same as Method Overriding

While variable hiding looks like overriding a variable (similar to method overriding), it is not. Overriding is applicable only to methods while hiding is applicable to variables.

In the case of method overriding, overridden methods completely replace the inherited methods, so when we try to access the method from a parent's reference by holding a child's object, the method from the child class gets called. You can read more about overriding on Everything About Method Overloading vs Method Overriding, Why We Should Follow Method Overriding Rules, and How Does the JVM Handle Method Overloading and Overriding Internally.

But in variable hiding, the child class hides the inherited variables instead of replacing them, so when we try to access the variable from the parent's reference by holding the child's object, it will be accessed from the parent class.

When an instance variable in a subclass has the same name as an instance variable in a super class, then the instance variable is chosen from the reference type.
public static void main(String[] args) throws Exception {

    Parent parent = new Parent();
    parent.printInstanceVariable(); // Output - "Parent's Instance Variable"
    System.out.println(parent.x); // Output - "Parent's Instance Variable"

    Child child = new Child();
    child.printInstanceVariable();// Output - "Child's Instance Variable, Parent's Instance Variable"
    System.out.println(child.x);// Output - "Child's Instance Variable"

    parent = child; // Or parent = new Child();
    parent.printInstanceVariable();// Output - "Child's Instance Variable, Parent's Instance Variable"
    System.out.println(parent.x);// Output - Parent's Instance Variable

    // Accessing child's variable from parent's reference by type casting
    System.out.println(((Child) parent).x);// Output - "Child's Instance Variable"
}


In above example, when we call the overridden method printInstanceVariable()onparent while holding the child's object in it, we can see the output is:

Child's Instance Variable, Parent's Instance Variable

Because in the child class, the method is printing the child class' x variable and super.x.

But when we call System.out.println(parent.variable); on the same parent reference that is holding the child's object, it prints Parent's Instance Variable because the new Child() object keeps the parent's x as well as the child's x and hides the parent's x. So, in this case, x is chosen from the class that is the reference type.

But if we wanted to access the child's variable even if we are using a parent reference, we can do that by using (Child) parent).variable.

When our variables are private or in another package and have default access, such variables are not visible outside of that class, and the child class cannot access them. So there no confusion — and that is why we should always stick to General Guidelines to create POJOs and declare our variables with private access (and also provide proper get/set methods to access them).

You can find the complete code on this GitHub Repository and please feel free to provide your valuable feedback.

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Topics:
java ,variable shadowing ,variable hiding ,java variables ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}