Java provides several modifiers that control access to data fields, methods , and classes. This section introduces the public , private , and default modifiers.
public makes classes, methods, and data fields accessible from any class.
private makes methods and data fields accessible only from within its own class.
If public or private is not used, then by default the classes, methods, and data fields are accessible by any class in the same package. This is known as package-private or package-access .
Figure 7.12 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.
If a class is not declared public, it can only be accessed within the same package, as shown in Figure 7.13.
A visibility modifier specifies how data fields and methods in a class can be accessed from the outside of the class. There is no restriction on accessing data fields and methods from inside the class. As shown in Figure 7.14(b), an object foo of the Foo class cannot access its private members , because foo is in the Test class. As shown in Figure 7.14(a), an object foo of the Foo class can access its private members, because foo is declared inside its own class.
Note
The private modifier applies solely to the members of a class (e.g., data fields or methods). The various Java modifiers are summarized in the table in Appendix D, "Java Modifiers." |
Note
Visibility modifiers are used for the members of the class, not local variables inside the methods. Using a visibility modifier on local variables would cause a compilation error. |
Note
In most cases, the constructor should be public. However, if you want to prohibit the user from creating an instance of a class, you can use a private constructor. For example, there is no reason to create an instance from the Math class because all of the data fields and methods are static. One solution is to define a dummy private constructor in the class. The Math class cannot be instantiated because it has a private constructor, as follows : |
private Math() { }
The Math class that comes with the Java system was introduced in §5.8, "The Math Class."