From JQPlus mock test: Consider following two classes: What will be the output of compiling and running class B ?
The correct answer is that it won't compile.The explanation says that
Although, class B extends class A and 'i' is a protected member of A, B still cannot access i, (now this is imp) THROUGH A's reference because B is not involved in the implementation of A. Had the process() method been defined as process(B b); b.i would have been accessible as B is involved in the implementation of B.
How can this be when a protected field is accessible from a subclass?I don't really understand the given explanation. jeff mutonho Edited by Corey McGlone: Added CODE Tags [ May 01, 2004: Message edited by: Corey McGlone ]
You are trying to access A-type object that is outside of the B class. The way inheritance works is that a subclass can extend functionality of the superclass, not have unlimited access to protected memebers of any object of the superclass. Instead of a.i = a.i*2; it should be: super.i = super.i*2; or simply: i = i*2; Andris [ May 01, 2004: Message edited by: Andris Jekabsons ]
I'm surprised that the similar code but without packages has been compiled.
There's a little clue in JLS pointed that protected affects only access outside the package. Correct me please, if I'm wrong.
6.6.2 Details on protected Access A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.
If you settle for what they are giving you, you deserve what you get. Fight for this tiny ad!