覆盖Java中的成员变量(变量隐藏) [英] Overriding member variables in Java ( Variable Hiding)
问题描述
我正在研究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?
推荐答案
在子类中创建相同名称的变量时,这称为隐藏.现在,生成的子类实际上将具有两者属性.您可以使用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中的成员变量(变量隐藏)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!