简体   繁体   English

子类访问中的受保护方法,它位于不同的包中

[英]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.

相关问题 受保护的为什么不能在不同的包子类中访问? - protected can't access in different package subclass why? 为什么不同包中的子类无法通过超类实例访问其在另一个包中的超类的受保护字段? - Why a subclass in a different package is unable to access the protected fields of its superclass in another package through superclass instance? Java访问不同包中子类中的受保护成员,使用父类型的对象引用 - Java access to protected member in subclass in different package, using object reference of parent type 当子类位于不同的包中时,为什么我的子类不能访问其超类的受保护变量? - Why can't my subclass access a protected variable of its superclass, when it's in a different package? 为什么另一个 package 中的子类无法访问受保护的方法? - Why subclass in another package cannot access a protected method? 为什么protected对于不同的子类包中的其他类变得私有 - why protected becomes private to other classes in different package of subclass 程序包访问类|(在公共和受保护之间有所不同) - package access class |(different between public and protected) Java:无法访问外部类的子类中嵌套类子类的受保护方法 - Java: Cannot access protected methods of nested class subclass in subclass of outer class 如何在子类中访问超类的“protected static”变量,其中子类位于不同的包中..? - How can ‘protected static’ variable of superclass be accessed in the subclass, where subclass resides in different package..? 为什么受保护的成员被放置在不同包中的类的子类的子类访问 - Why protected member is accessed by subclass of subclass of a class which are placed in different packages
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM