This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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.
Joined: Aug 27, 2004
Hello Harshil, Thanks for Quick Reply...Now even if i comment the code of display()in Pqrs(Referring to code given earlier)i amgetting the same error Shrinivas
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...)
Hope this helps.
Joined: Aug 27, 2004
Hello Jon, Thanks a Lot for quick reply.... well there is one more change i have observed in your reply
Do you want to say that if i create the instance of Abcd class in Pqrs's main then also i can't access protected method & variable of Abcd something done in original code.....