saravanan
saravanan

Reputation: 5417

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
   }

}

Upvotes: 1

Views: 893

Answers (1)

Tudor
Tudor

Reputation: 62469

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.

Upvotes: 4

Related Questions