看起来很傻,但我真的很困惑。请看下面的代码:
package com.one;
public class SuperClass {
protected void fun() {
System.out.println("base fun");
}
}
----
package com.two;
import com.one.SuperClass;
public class SubClass extends SuperClass{
public void foo() {
SuperClass s = new SuperClass();
s.fun(); // Error Msg: Change visibility of fun() to public
}
}
我已阅读oracle doc和here同样, protected 成员在另一个包的子类中也可见。所以 fun() 应该在包二的子类中可见。那为什么会报错呢?
我是否严重遗漏了一些非常明显的东西?
最佳答案
A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.
这意味着,如果您在原始类的包之外编写子类,则每个对象都可以在自身上调用父类(super class)的 protected 方法,但不能在其他对象上调用。
在您的示例中,由于 s
与 this
是不同的对象,因此您无法调用 s.fun()
。但该对象可以通过 this.fun()
或仅使用 fun()
调用自身的 fun
方法。
关于java - 父类(super class)中的 protected 方法在不同包中的子类中是否可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47800155/