[英]Protected methods in subclass access which is in different package
I Have following two classes: 我有两节课:
Class A A级
package A;
public class A {
protected String classType(){
return "s1";
}
}
Class C C级
package B;
import A.A;
public class C extends A{
public static void main(String[] args){
C c=new C();
c.classType();//no error
A a=new C();
a.classType();//error
}
}
Why error occurs in second one,even though we are accessing protected methods which is said to have access in subclass in different package?? 为什么错误发生在第二个,即使我们访问受保护的方法,据说在不同的包中的子类中访问?
Access to protected
methods is granted across packages within the context of a class extending the parent class. 在扩展父类的类的上下文中,跨包提供对protected
方法的访问。
In your case, you are invoking that method on an instance of the class, hence it is not visible. 在您的情况下,您在类的实例上调用该方法,因此它不可见。
It would be if you had an instance method or statement in C
invoking classType()
: that would virtually invoke super#classtype()
unless you'd overridden it in C
. 如果您在C
调用classType()
有一个实例方法或语句:除非您在C
重写它,否则它将虚拟调用super#classtype()
。
Eg 例如
public class C extends A {
{
// ok, instance statement
String foo = classType();
}
void foo() {
// ok, instance method
String foo = classType();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.