Java Reference
In-Depth Information
Note
Packages can be used to organize classes. To do so, you need to add the following line
as the first noncomment and nonblank statement in the program:
using packages
package
packageName;
If a class is defined without the package statement, it is said to be placed in the
default
package
.
Java recommends that you place classes into packages rather than using a default pack-
age. For simplicity, however, this topic uses default packages. For more information on
packages, see Supplement III.E, Packages.
In addition to the
public
and default visibility modifiers, Java provides the
private
and
protected
modifiers for class members. This section introduces the
private
modifier.
The
protected
modifier will be introduced in Section 11.14, The
protected
Data and
Methods.
The
private
modifier makes methods and data fields accessible only from within its own
class. Figure 9.14 illustrates how a public, default, and private data field or method in class
C1
can be accessed from a class
C2
in the same package and from a class
C3
in a different
package.
package
p1;
package
p1;
package
p2;
public class
C1 {
public int
x;
int
y;
private int
z;
public class
C2 {
void
aMethod() {
C1 o =
new
C1();
can access o.x;
can access o.y;
cannot access o.z;
public class
C3 {
void
aMethod() {
C1 o =
new
C1();
can access o.x;
cannot access o.y;
cannot access o.z;
public void
m1() {
}
void
m2() {
}
private void
m3() {
}
}
can invoke o.m1();
can invoke o.m2();
cannot invoke o.m3();
}
}
can invoke o.m1();
cannot invoke o.m2();
cannot invoke o.m3();
}
}
F
IGURE
9.14
The private modifier restricts access to its defining class, the default modifier restricts access to a package,
and the public modifier enables unrestricted access.
If a class is not defined as public, it can be accessed only within the same package. As
shown in Figure 9.15,
C1
can be accessed from
C2
but not from
C3
.
package
p1;
package
p1;
package
p2;
class
C1 {
...
}
public
class C2 {
can access C1
}
public class
C3 {
cannot access C1;
can access C2;
}
F
IGURE
9.15
A nonpublic class has package-access.
A visibility modifier specifies how data fields and methods in a class can be accessed from
outside the class. There is no restriction on accessing data fields and methods from inside the
class. As shown in Figure 9.16b, an object
c
of class
C
cannot access its private members,
because
c
is in the
Test
class. As shown in Figure 9.16a, an object
c
of class
C
can access its
private members, because
c
is defined inside its own class.
inside access
Search WWH ::
Custom Search