本文介绍了覆盖 Java 中的成员变量(变量隐藏)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究 JAVA 中的覆盖成员函数,并考虑尝试覆盖成员变量.

I am studying overriding member functions in JAVA and thought about experimenting with overriding member variables.

所以,我定义了类

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

输出为:

1
I am class A
1
I am class B

我不明白为什么当 aRef 设置为 b 时 intVal 仍然属于 A 类?

I am not able to understand why when aRef is set to b intVal is still of class A?

推荐答案

当您在子类中创建同名变量时,这称为隐藏.生成的子类现在实际上将具有 both 属性.您可以使用 super.var((SuperClass)this).var 从超类访问一个.变量甚至不必是同一类型;它们只是两个共享一个名称的变量,很像两个重载的方法.

When you make a variable of the same name in a subclass, that's called hiding. The resulting subclass will now actually have both properties. You can access the one from the superclass with super.var or ((SuperClass)this).var. The variables don't even have to be of the same type; they are just two variables sharing a name, much like two overloaded methods.

这篇关于覆盖 Java 中的成员变量(变量隐藏)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:39
查看更多