Home > Java > javaTutorial > Can Java Subclasses Override Member Variables?

Can Java Subclasses Override Member Variables?

DDD
Release: 2024-12-18 18:15:10
Original
944 people have browsed it

Can Java Subclasses Override Member Variables?

Overriding Member Variables in Java: Understanding Variable Hiding

In Java, overriding member functions is a well-known concept, but what about overriding member variables? To explore this, consider the following 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); // Output: 1
        aRef.identifyClass(); // Output: "I am class A"
        aRef = b;
        System.out.println(aRef.intVal); // Output: 1
        aRef.identifyClass(); // Output: "I am class B"
    }
}
Copy after login

The code aims to demonstrate the behavior of overridden member variables. However, there's a puzzle - why does aRef.intVal still return 1 after aRef is set to b, which has a intVal of 2?

The answer lies in the concept of variable hiding. When a subclass declares a variable with the same name as one in its superclass, it "hides" the superclass's variable. This means that the subclass has two variables: one from its superclass and one from its own definition.

In the code above, the intVal member variable is declared in both A and B. Therefore, when B is created, it has both intVals - one with a value of 1 inherited from A, and one with a value of 2 defined in B.

When aRef is set to a, it refers to the intVal of A. When aRef is set to b, it still refers to the intVal of A. This is because in the expression aRef.intVal, aRef resolves to the type A, and intVal is a variable of A.

To access the intVal of B, one would need to use ((B)aRef).intVal, which explicitly casts aRef to type B and allows access to B's variables.

The above is the detailed content of Can Java Subclasses Override Member Variables?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template