Variable hiding occurs when a subclass defines a member variable with the same name as a member variable in its superclass. Unlike function overriding, which replaces the implementation, variable hiding obscures the superclass variable with a new variable of the same name.
Consider the following Java code:
public class A { public int intVal = 1; public void identifyClass() { System.out.println("I am class A"); } } public class B extends A { public int intVal = 2; public void identifyClass() { System.out.println("I am class B"); } } public 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(); } }
Output:
1 I am class A 1 I am class B
In this example, the intVal variable is defined in both the A and B classes. The member variable of B hides the one from A. As a result, when aRef is set to b, the intVal value accessed is still 1, which is the default value of A's intVal.
To access the hidden variable of the superclass, we can use super.var or ((SuperClass)this).var. For example:
aRef = b; System.out.println(aRef.intVal); // Outputs 1, the value of A's intVal System.out.println(((A)aRef).intVal); // Outputs 2, the value of B's intVal
By explicitly casting aRef to its superclass, we can access the hidden member variable.
Remember, variable hiding allows subclasses to define their own variables with the same names as superclass variables, but it does not fully override them. Both variables coexist, and the subclass variable shadows the superclass variable.
The above is the detailed content of How Does Variable Hiding in Java Differ from Function Overriding?. For more information, please follow other related articles on the PHP Chinese website!