"AIK" <as*******@hotmail.com.error> wrote in news:u5BUc.457$euc.91
@news04.bloor.is.net.cable.rogers.com:
I have the following two classes:
package birdpack;
public class Bird {
Bird() {}
protected int nFeathers;
}
in bird.java
and
package duckpack;
import birdpack.Bird;
public class Duck3 extends Bird {
Duck3() {}
void foo() {
Bird b = new Bird();
int temp;
temp = b.nFeathers;
}
}
in Duck3.java
When I compile Duck3 I get this error: nFeathers has protected access in
birdpack.Bird. Why is this? I thought the point of a protected modifier
is to allow children of a class to access parent's protected feature even if
the child class is in a different package?
Yes, that is the point, but there are rules to follow.
You can see the rules in section 6.6.2 of the Java Language Specification
at
http://java.sun.com/docs/books/jls/f...doc.html#33916
The rules appear to be designed in part so that a subclass may maintain the
protected fields of its superclass (of the same instance). When you access
a superclass field of a different instance, you are no longer providing
maintenance of your object. (My language here is inexact; The JLS is
exact but can be difficult to penetrate).
If you had written
temp = super.nFeathers ;
I think that you would meet the rules. You would be accessing the
nFeathers associated with the parent of the Duck3 that you are maintaining.
By creating a new Bird and attempting to access its nFeathers field, you
would be accessing a protected field of an object that is NOT implemented
by this code.
Why does Duck3 (which is already a Bird) need to create another Bird
anyway?
Bird b = new Bird();
is a strange thing to have in Duck3.
--
Ian Shef
These are my personal opinions and not those of my employer.