Home > Java > javaTutorial > How Does Variable Hiding in Java Differ from Function Overriding?

How Does Variable Hiding in Java Differ from Function Overriding?

Linda Hamilton
Release: 2024-12-17 08:12:25
Original
292 people have browsed it

How Does Variable Hiding in Java Differ from Function Overriding?

Understanding Member Variable Hiding (Overriding) in Java

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();
    }
}
Copy after login

Output:

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

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
Copy after login

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!

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