Java Reference
In-Depth Information
A Visibility Example
Consider the highly contrived situation depicted in the Figure E.2 Class
P
is the
parent class that is used to derive child classes
C1
and
C2
. Class
C1
is in the same
package as
P
, but
C2
is not. Class
P
contains four methods, each with different
visibility modifiers. One object has been instantiated from each of these classes.
The
public
method
a()
has been inherited by
C1
and
C2
, and any code with
access to object
x
can invoke
x.a()
. The
private
method
d()
is not visible to
C1
or
C2
, so objects
y
and
z
have no such method available to them. Furthermore,
d()
is fully encapsulated and can be invoked only from within object
x
.
The
protected
method
b()
is visible in both
C1
and
C2
. A method in
y
could
invoke
x.b()
, but a method in
z
could not. Furthermore, an object of any class
in package
One
could invoke
x.b()
, even those that are not related to class
P
by
inheritance, such as an object created from class
Another1
.
Method
c()
has
default
visibility, since no visibility modifier was used to
declare it. Therefore object
y
can refer to the method
c()
as if it were declared
locally, but object
z
cannot. Object
y
can invoke
x.c()
, as can an object instanti-
ated from any class in package
One
, such as
Another1
. Object
z
cannot invoke
x.c()
.
These rules generalize in the same way for variables. The visibility rules may
appear complicated initially, but they can be mastered with a little effort.
package One
class P
P x = new P();
C1 y = new C1();
C2 z = new C2();
public a()
protected b()
c()
private d()
class Another1
package Two
class C1
class C2
class Another2
FIGURE E.2
A situation demonstrating Java visibility modifiers
Search WWH ::
Custom Search