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 using a default package. For
simplicity, however, this topic uses default packages. For more information on packages,
see Supplement III.G, 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.13, The protected Data and Methods.
The private modifier makes methods and data fields accessible only from within its own
class. Figure 8.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 pack-
age.
package p1;
package p1;
package p2;
public class C1 {
public int x;
int y;
private int z;
public class C2 {
void aMethod() {
public class C3 {
void aMethod() {
C1 o = new C1();
C1 o = new C1();
can access o.x;
can access o.y;
cannot access o.z;
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 8.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 8.15, C1 can be accessed from C2 but not from C3 .
package p1;
package p1;
package p2;
public class C2 {
can access C1
public class C3 {
cannot access C1;
can access C2;
class C1 {
...
}
}
}
F IGURE 8.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 8.16b, an object c of class C cannot access its private members,
because c is in the Test class. As shown in Figure 8.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