简体   繁体   中英

why protected becomes private to other classes in different package of subclass

why protected becomes private to other classes in different package of subclass .but it is still protected in same package of super class.

package a;
class A
{
  protected a;
}

package b;
class B extends A
{
  B()
{
  System.out.println(a);
}
}

class C
{
  C()
  {
    System.out.println(new B().a);//error
   }

}

Because the package is the "visibility limit" of the protected access modifier for non-related classes. See the docs here: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html :

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

As you can see from the above, you are neither in the case of subclass, nor in the case of same package.

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