DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Singleton: 6 Ways To Write and Use in Java Programming
  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling

Trending

  • Teradata Performance and Skew Prevention Tips
  • AI's Dilemma: When to Retrain and When to Unlearn?
  • Rust and WebAssembly: Unlocking High-Performance Web Apps
  • Analyzing “java.lang.OutOfMemoryError: Failed to create a thread” Error
  1. DZone
  2. Coding
  3. Java
  4. Variable Shadowing and Hiding in Java

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.

By 
Naresh Joshi user avatar
Naresh Joshi
DZone Core CORE ·
Updated Feb. 16, 18 · Tutorial
Likes (16)
Comment
Save
Tweet
Share
84.0K Views

Join the DZone community and get the full member experience.

Join For Free

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).

Do you want to know more about variable hiding?, In the article Why Instance Variable Of Super Class Is Not Overridden In SubClass, I have discussed why variables do not follow overriding, why variable hiding is not designed same as method overriding and why instance variable is chosen from reference type instead of the object? Please go ahead and read it.

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

Instance variable Java (programming language)

Published at DZone with permission of Naresh Joshi, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Singleton: 6 Ways To Write and Use in Java Programming
  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!