1. package package2; 2. import package1; 3. class ChildClass extends ParentClass { 4. public static void main (String [] args) { 5. ChildClass cc = new ChildClass(); 6. System.out.print("child " + cc.x); 7. ParentClass pc = new ParentClass(); 8. System.out.print(" parent " + pc.x); 9. } 10. }
My question is why line 8 is giving error. As child class has extended the parent class, so the child class can see what is there in the parent class so why cant the object of parent class use the X while child class object can use it.
Calling cc.x is correct because you're trying to access a protected field from the same package than ChildClass.
Calling pc.x is NOT correct necause you're trying to access a protected fiels : - from a different package. - not from an instance of a subclass of ParentClass.
Hi patrick! Protected member outside the package are accesible only and only and only through inheritance. You can not access them through a reference of parent class.
ok that means when ever a protected scope comes across packages then packages take the priority and we consider every thing in scope of packages...Right?
First there is class scope... you check out whether class is visible across packages or not. If yes, only then comes the question if the member is accessible or not.
There is very good explanation provided by Kathy in one if the discussion threads.
To summarize
1) if a class has protected access modifier on a member variable/function, then the member variable is exposed as default access to all classes in the same package.
2) To all classes outside the package, in which the class containing the protected member is defined,irrespective of the visibility of the class being public, the protected member is seen to be private, except for classes that subclass the class containing the protected variable.
3) A subclass-outside-package, can access the protected member only through inheritance, and cannot access using a reference of the super class. Trying to refer to the protected member of the super class will throw a compilation error. This is the reason why you get the compilation error in your code.
4)The inherited protected member of subclass-outside-package cannot be accessed by any other class of the same package of subclass-outside-package class, except for classes that are subclasses of the subclass-outside-package.
The major difference between protected and default access is default is only within the same package and protected is same package + kids(even if the subclass is present in a different package).
Hope this explanation helps. I would suggest that you do a search and try to find explanation provided by Kathy.
Post by:autobot
It looks like it's time for me to write you a reality check! Or maybe a tiny ad!
a bit of art, as a gift, the permaculture playing cards