Hello Friends, I have a very basic doubt related to protected access specifier...Kindly see the following code ...I am not getting why there is a compile time error..I am using JDK1.4.... Class Abcd in Package x
Class Pqrs in package y extends Abcd in x
C:\>javac -d . Pqrs.java Pqrs.java:15: display() has protected access in x.Abcd a.display();
6.6.2 Details on protected Access [B] A protected member or constructor of an object may be accessed from outside the package in which it is declared [b]only by code that is responsible for the implementation of that object.
In the code instance of class Abcd is trying to call the protected method which is implemented by class Pqrs. So the error.
I disagree with that interpretation. Here's my understanding:
When a class has a protected member, it is available to subclasses outside the package through inheritance only. That is, a subclass can't access a protected member of an instance of the superclass, but it can access an inherited copy of that member in an instance of the subclass. So, Pqrs can't access Abcd.display().... but it can access Pqrs.display(), which is inherited from Abcd. Here's the example that compiles and runs for me:
This class is unchanged:
When the y.Pqrs class is run, the results are: "In Abcd"
(If you change the name of the "Pqrs" method back to "display()", you get "In Pqrs" - but it becomes an uninteresting case, since you would have the same result if the Abcd class never existed, or the Abcd.display() method was private...)