简体   繁体   中英

Protected methods in subclass access which is in different package

I Have following two classes:

Class A

package A;
public class A {
    protected String classType(){
        return "s1";
    }
}

Class 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.

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 .

Eg

public class C extends A {
    {
        // ok, instance statement
        String foo = classType();
    }
   void foo() {
        // ok, instance method
        String foo = classType();
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM