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
-
Have a look at this cheat sheet: http://stackoverflow.com/a/33627846/276052 – aioobe Mar 09 '16 at 22:22
2 Answers
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

- 46,488
- 10
- 44
- 88
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.

- 2,294
- 18
- 27