gpt4 book ai didi

java - 现场阴影还是覆盖?

转载 作者:行者123 更新时间:2023-12-02 06:08:49 27 4
gpt4 key购买 nike

我有两个类(A 和 B),B 扩展了 A。

public class A {
protected int i = 1;
}

public class B extends A{
protected int i = 2;
}

在本例中,程序写入 1。

A a = new B();
System.out.println(a.i); //1

但是如果我在构造函数中分配值 i,它会写入 2。

public class B extends A{
public B(){
i=2;
}
}

A a = new B();
System.out.println(a.i); //2

为什么?

最佳答案

来自the official doc :

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. Within the subclass, the field in the superclass cannot be referenced by its simple name. Instead, the field must be accessed through super, which is covered in the next section. Generally speaking, we don't recommend hiding fields as it makes code difficult to read.

字段不是多态的,并且您保留对 A 对象的引用。通过执行 i = 2,您可以更改字段的值,从而修改结果。

相关问题:Hiding Fields in Java Inheritance

关于java - 现场阴影还是覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22053413/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com