0

Why a protected method of parent class in one package cannot be accessed using the parent reference in its child class which is in different package. [A.java][[]][1][1]]2

2 Answers2

0

The scope of protected is within the package. You can't access it from another package, even if you have an instance of the class.

Scope table from Oracle documentation

Modifier    Class   Package Subclass    World
public      Y       Y       Y           Y
protected   Y       Y       Y           N
no modifier Y       Y       N           N
private     Y       N       N           N
Guy
  • 46,488
  • 10
  • 44
  • 88
0

Its by convention - that is what protected is defined to do. Protected members in the child class only through inheritance. No other way.

Lets assume we can access the protected member in the child class which is in a different package using parent class instance.

Now, how would you differentiate in your child class - if the member was declared public or protected? Also, if it is accessible using the parent instance, then why access it only from child class? It should be accessible from anywhere using parent class instance.

I hope, if you ask these questions to yourself - it will all start making sense.

Tirath
  • 2,294
  • 18
  • 27