为什么另一个包中的子类无法访问受保护的方法? [英] Why subclass in another package cannot access a protected method?
问题描述
我在两个不同的包中有两个类:
I have two classes in two different packages:
package package1;
public class Class1 {
public void tryMePublic() {
}
protected void tryMeProtected() {
}
}
package package2;
import package1.Class1;
public class Class2 extends Class1 {
doNow() {
Class1 c = new Class1();
c.tryMeProtected(); // ERROR: tryMeProtected() has protected access in Class1
tryMeProtected(); // No error
}
}
我能理解为什么没有调用 tryMeProtected()
时出错,因为 Class2
看到此方法,因为它继承自 Class1
。
I can understand why there is no error in calling tryMeProtected()
since Class2
sees this method as it inherits from Class1
.
但为什么 Class2
的对象无法访问此方法在 Class1
的对象上使用 c.tryMeProtected();
?
But why isn't it possible for an object of Class2
to access this method on an object of Class1
using c.tryMeProtected();
?
推荐答案
受保护的方法只能通过包之外的子类中的继承来访问。因此第二种方法 tryMeProtected();
有效。
Protected methods can only be accessible through inheritance in subclasses outside the package. And hence the second approach tryMeProtected();
works.
下面的代码不会编译因为我们没有调用继承的受保护方法版本。
The code below wont compile because we are not calling the inherited version of protected method.
Class1 c = new Class1();
c.tryMeProtected(); // ERROR: tryMeProtected() has protected access in Class1
按照stackoverflow 链接以获取更多解释。
Follow this stackoverflow link for more explaination.
这篇关于为什么另一个包中的子类无法访问受保护的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!