问题描述
我在两个不同的包中有两个类:
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.
这篇关于为什么另一个包中的子类不能访问受保护的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)