我在两个不同的包中有两个类:
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模板网!
如何检测 32 位 int 上的整数溢出?How can I detect integer overflow on 32 bits int?(如何检测 32 位 int 上的整数溢出?)
return 语句之前的局部变量,这有关系吗?Local variables before return statements, does it matter?(return 语句之前的局部变量,这有关系吗?)
如何将整数转换为整数?How to convert Integer to int?(如何将整数转换为整数?)
如何在给定范围内创建一个随机打乱数字的 intHow do I create an int array with randomly shuffled numbers in a given range(如何在给定范围内创建一个随机打乱数字的 int 数组)
java的行为不一致==Inconsistent behavior on java#39;s ==(java的行为不一致==)
为什么 Java 能够将 0xff000000 存储为 int?Why is Java able to store 0xff000000 as an int?(为什么 Java 能够将 0xff000000 存储为 int?)