gpt4 book ai didi

java - 为什么我们可以降低扩展类中属性的可见性?

转载 作者:太空狗 更新时间:2023-10-29 22:42:57 25 4
gpt4 key购买 nike

我有两个类,Parent:

public class Parent {
public String a = "asd";

public void method() {

}
}

child :

public class Child extends Parent{
private String a = "12";

private void method() {

}
}

Child 中,我尝试覆盖父级 method,它给出了编译时错误 cannot reduce visibility of a method 这很好.

但是,为什么这个错误不适用于属性 a?我还降低了 a 的可见性,但它没有给出错误。

最佳答案

这是因为Parent.aChild.a 是不同的东西。 Child#method() @Override Parent#method(),因为它们是方法。继承不适用于字段。

From the Oracle JavaTM Tutorials - Inheritance, it was written that:

What You Can Do in a Subclass

  • The inherited fields can be used directly, just like any other fields.
  • You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended).
  • You can declare new fields in the subclass that are not in the superclass.

关于java - 为什么我们可以降低扩展类中属性的可见性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24719880/

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