Iam preparing for SCJP , also i came to know that protected members scope is within the package as well as in other package with some conditions like possible only with inheritance.
For example : i have three classes as Parentclass Childclass Friendclass
package x.parent;
class Parentclass{
protected int x=10;
...............
}
package x.child;
class Childlass extends Parentclass{
super.x=20;
...............
}
package x.child;
import x.parent.Parentclass;
class Friendclass{
Parentclass pc = new Parentclass();
pc.x=30;
...............
}
Whats the reason behind that, in Friendclass the member x will not accept to assign a value to that, behaves as private member not in case of Childclass.
There are four access modifiers
Since it uses the default modifier, it has access if one of the following is true:
So it fails the criteria, and so you don't get access.
You can't even access
Parentclass.x
inChildclass
becausex
has default visibility (not protected). See http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.htmledit:
x.child.Friendclass
is not in the same package asx.parent.Parentclass
.x.child.Friendclass
does not inherit fromx.parent.Parentclass
.as TotalFrickinRockstarFromMars's summary states and the Java access control docs also state, this means that
Friendclass
is not allowed to access the fieldx
.