Java Reference
In-Depth Information
T ABLE 11.2
Data and Methods Visibility
Modifier
on members
in a class
Accessed
from the
same class
Accessed
from the
same package
Accessed from
a subclass in a
different package
Accessed
from a different
package
public
-
protected
-
-
default (no modifier)
-
-
-
private
package p1 ;
public class C1 {
public int x;
protected int y;
int z;
private int u;
public class C2 {
C1 o = new C1();
can access o.x;
can access o.y;
can access o.z;
cannot access o.u;
protected void m() {
}
}
can invoke o.m();
}
package p2;
public class C3
extends C1 {
can access x;
can access y;
can access z;
cannot access u;
public class C4
extends C1 {
can access x;
can access y;
cannot access z;
cannot access u;
public class C5 {
C1 o = new C1();
can access o.x;
cannot access o.y;
cannot access o.z;
cannot access o.u;
can invoke m();
}
can invoke m();
}
cannot invoke o.m();
}
F IGURE 11.5
Visibility modifiers are used to control how data and methods are accessed.
for use from outside the class. Make the members public if they are intended for the users of
the class. Make the fields or methods protected if they are intended for the extenders of the
class but not for the users of the class.
The private and protected modifiers can be used only for members of the class. The
public modifier and the default modifier (i.e., no modifier) can be used on members of the
class as well as on the class. A class with no modifier (i.e., not a public class) is not accessi-
ble by classes from other packages.
Note
A subclass may override a protected method defined in its superclass and change its vis-
ibility to public. However, a subclass cannot weaken the accessibility of a method
defined in the superclass. For example, if a method is defined as public in the superclass,
it must be defined as public in the subclass.
change visibility
Search WWH ::




Custom Search