Hi, All,
I'm working on
SCJP and have a question about access to protected member. I hope someone can give me some hint on it.
In one source file, Parent.java, I have:
-------------
package cert;
public class Parent {
protected int i = 3;
}
--------------
In the second file, ChildOutsidePackage.java, I have:
------------
package noncert;
import cert.Parent;
class ChildOutsidePackage extends Parent {
public static void main(
String[] args) {
ChildOutsidePackage c = new ChildOutsidePackage();
System.out.println("c.i = " + c.i);
GrandChildOutsidePackage gchild = new GrandChildOutsidePackage();
System.out.println("gchild.i = " + gchild.i);
Neighbor n = new Neighbor();
System.out.println("n.neighborc.i = " + (++n.neighborc.i));
}
}
class GrandChildOutsidePackage extends ChildOutsidePackage { }
class Neighbor {
public ChildOutsidePackage neighborc = new ChildOutsidePackage();
}
--------------------------------------------------------------
Below is the output:
------------------------
build$ javac -d . -classpath . ../ChildOutsidePackage.java
build$
java noncert.ChildOutsidePackage
c.i = 3
gchild.i = 3
n.neighborc.i = 4
------------------------
I understand that ChildOutsidePackage and GrandChildOutsidePackage have access to the protected member i through inheritance. What bothers me is why Neighbor has access to i. Class Neighbor is in a package different from class Parent and it is not its subclass. Isn't the protected member i supposed be invisible to class Neighbor?
I know it is a kind of odd to place an instance of Neighbor inside of the main() of class ChildOutsidePackage. If I move the main() to class Neighbor as follows,
----------------------
package noncert;
import cert.Parent;
class ChildOutsidePackage extends Parent { }
class GrandChildOutsidePackage extends ChildOutsidePackage { }
class Neighbor {
public ChildOutsidePackage neighborc = new ChildOutsidePackage();
public static void main(String[] args) {
ChildOutsidePackage c = new ChildOutsidePackage();
System.out.println("c.i = " + c.i);
GrandChildOutsidePackage gchild = new GrandChildOutsidePackage();
System.out.println("gchild.i = " + gchild.i);
Neighbor n = new Neighbor();
System.out.println("n.neighborc.i = " + n.neighborc.i);
}
}
----------------------
The program can't compile, which is expected:
----------------------
build$ javac -d . -classpath . ../ChildOutsidePackage.java
../ChildOutsidePackage.java:28: i has protected access in cert.Parent
System.out.println("c.i = " + c.i);
^
../ChildOutsidePackage.java:31: i has protected access in cert.Parent
System.out.println("gchild.i = " + gchild.i);
^
../ChildOutsidePackage.java:34: i has protected access in cert.Parent
System.out.println("n.neighborc.i = " + n.neighborc.i);
^
3 errors
-----------------------
Could anyone give some explanation? Thanks in advance.