Hi there,
I have a question regarding protected modifier.
referring to Kathy and Bert book on Sun
java cert prog, on page 79,80.
I attached the paragraph from page 79 and 80.
But there is still one more issue we haven;t looked at..what does a protected member look like to other classes trying to use the subclass-outside-the-package to get the subclass' inherited protected superclass member? FOr example, using our previous Parent/Child classes, what happens if some other class--Neighbour, say in the same package as the Child(subclass), has a reference to a Child instance and want to access the member variable x? In other words, how does that protected member behave once the subclass has inherited it? Does it maintain its protected status, such that classes in the Child's package can see it?
No! Once the subclass-outisde-the-package inherits the protected member, that member(as inherited by the subclass) becomes private to any code outside the subclass. So if class Neighbour instantiates a Child object, then even if class Neighbour is in the same package as class Child, class Neighbour won't have access to the Child inherited(but protected) variable x. The button line : when a subclass-outside-the package inherits the protected member, the member is essentially private inside the subclass, such that only the subclass own code can access it.
package certification;
public class Parent{
protected int x = 9;
}
package other;
import certification.Parent;
class Child extends Parent{
public void
test(){
System.out.println(x);
}
}
package other; // Neighbour and Child class are located in the same package
class Neighbour {
static public void main(
String[] ar){
// create a reference to a Child Object
Child c = new Child();
System.out.println(c.x); // (1) this is what i don;t understand
// the value is still accessible from this class
}
}
Note: the code are in different files.
It is contradict with what the book said, the protected variable x still accessible from Neighbour class.
quote:
--------------------------------------------------------------------------
"So if class Neighbour instantiates a Child object, then even if class Neighbour is in the same package as class Child, class Neighbour won't have access to the Child inherited(but protected) variable x"
-------------------------------------------------------------------------
I think i misunderstood the concept, could any one of you help me to solve the problem.
Sorry if my question is not to the point.
thanks