Why subclass in another package cannot access a protected method?(为什么另一个包中的子类不能访问受保护的方法?)
问题描述
我在两个不同的包中有两个类:
package package1;公共类 Class1 {公共无效tryMePublic(){}受保护的无效tryMeProtected(){}}包包2;导入包1.Class1;公共类 Class2 扩展 Class1 {现在做() {Class1 c = new Class1();c.tryMeProtected();//错误:tryMeProtected() 在 Class1 中具有受保护的访问权限tryMeProtected();//没有错误}}我可以理解为什么调用 tryMeProtected() 没有错误,因为 Class2 认为这个方法继承自 Class1.p>
但是为什么 Class2 的对象不能使用 c.tryMeProtected(); 访问 Class1 的对象上的这个方法;代码>?
受保护的方法只能通过在包外的子类中继承来访问.因此,第二种方法 tryMeProtected(); 有效.
下面的代码不会编译,因为我们没有调用受保护方法的继承版本.
Class1 c = new Class1();c.tryMeProtected();//错误:tryMeProtected() 在 Class1 中具有受保护的访问权限关注这个 stackoverflow 更多解释的链接.
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
}
}
I can understand why there is no error in calling tryMeProtected() since Class2 sees this method as it inherits from Class1.
But why isn't it possible for an object of Class2 to access this method on an object of Class1 using c.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
Follow this stackoverflow link for more explaination.
这篇关于为什么另一个包中的子类不能访问受保护的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么另一个包中的子类不能访问受保护的方法?
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
