Java继承字段 [英] Java inheritance fields
问题描述
我无法理解以下输出。
我不知道为什么输出为10,我认为该行 A a = new B()
创建一个B类的新实例,我认为结果应为20
I don't know why the output is 10, I think the line A a = new B()
creates a new instance of class B, I think the result should be 20
class A {
int i = 10;
}
class B extends A {
int i = 20;
}
public class MainClass {
public static void main(String[] args) {
A a = new B();
System.out.println(a.i);
}
}
为什么会这样工作..请解释。
Why this works like this .. please explain.
推荐答案
首先,参见 隐藏字段 (强调添加)
First, see Hiding Fields (emphasis added)
在一个类中,与超类中的字段同名的字段会隐藏超类的字段,即使它们的类型不同
Within a class, a field that has the same name as a field in the superclass hides the superclass's field, even if their types are different
换句话说,这不是继承,因为你实际上是在隐藏 A
的我
在 B
后面 i
后面,你正在使用一个参考对象 A
,所以你得到它的字段。如果你做了 B b = new B()
,你会看到 20
,如预期的那样。
In other words, this isn't "inheritance" since you're actually hiding A
's i
behind B
's i
, and you are using a reference object of A
, so you are getting its fields. If you did B b = new B()
, you would see 20
, as expected.
如果您期望真正的覆盖,请尝试使用方法。
If you expect true overrides, try using methods.
class A {
public int get() {
return 10;
}
}
class B extends A {
@Override
public int get() {
return 20;
}
}
参见
A a = new B();
System.out.print(a.get()); // 20
如果你真的想看到两者马上看这个例子。
If you really want to see both at once, see this example.
class A {
int i = 10;
}
class B extends A {
int i = 20;
@Override
public String toString() {
return String.format("super: %d; this: %d", super.i, this.i);
}
}
和
A a = new B();
System.out.print(a); // super: 10; this: 20
这篇关于Java继承字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!