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(); } }
Executing this code produced the following output:
1 I am class A 1 I am class B
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!