Home > Java > javaTutorial > Why Does Variable Hiding Occur When Overriding Member Variables in Java?

Why Does Variable Hiding Occur When Overriding Member Variables in Java?

Linda Hamilton
Release: 2024-12-20 20:02:10
Original
337 people have browsed it

Why Does Variable Hiding Occur When Overriding Member Variables in Java?

Revealing the Nuances of Variable Hiding in Java

While exploring the concept of overriding member functions in Java, you ventured into experimenting with overriding member variables. To that end, you crafted the following class structure:

class A {
    public int intVal = 1;
}

class B extends A {
    public int intVal = 2;
}

class MainClass {
    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        A aRef;
        aRef = a;
        System.out.println(aRef.intVal);
        aRef.identifyClass();
        aRef = b;
        System.out.println(aRef.intVal);
        aRef.identifyClass();
    }
}
Copy after login

Executing this code produced the following output:

1
I am class A
1
I am class B
Copy after login

You expressed confusion over why aRef.intVal remained 1 even after being assigned to an instance of class B. To unravel this mystery, understand that in the scenario you presented, you are dealing with variable hiding rather than overriding.

In Java, you can have a variable with the same name in a superclass and a subclass. This variable hiding technique effectively hides the superclass variable. However, both variables continue to exist independently within their respective classes.

When you access the variable from a reference of the superclass, you're interacting with the superclass variable. The reference itself is not impacted by the class of the object it points to. Therefore, even though aRef is pointing to an instance of class B, it accesses the intVal variable from class A because that's the class to which aRef belongs.

To access the intVal variable from the subclass (B), you can utilize the super keyword, which references the superclass. This approach allows you to distinguish between the variables with the same name in the superclass and subclass, thereby resolving any ambiguity.

The above is the detailed content of Why Does Variable Hiding Occur When Overriding Member Variables in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template