DEV Community

Cover image for Visibility Modifiers
Paul Ngugi
Paul Ngugi

Posted on

Visibility Modifiers

Visibility modifiers can be used to specify the visibility of a class and its members. You can use the public visibility modifier for classes, methods, and data fields to denote that they can be accessed from any other classes. If no visibility modifier is 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.

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:

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 package.

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 private modifier makes methods and data fields accessible only from within its own class. Figure below 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.

Image description

If a class is not defined as public, it can be accessed only within the same package. As shown below, C1 can be accessed from C2 but not from C3.

Image description

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 below (b), an object c of class C cannot access its private members, because c is in the Test class. As shown in Figure below (a), an object c of class C can access its private members, because c is defined inside its own class.

Image description

The private modifier applies only to the members of a class. The public modifier can apply to a class or members of a class. Using the modifiers public and private on local variables would cause a compile error.

In most cases, the constructor should be public. However, if you want to prohibit the user from creating an instance of a class, use a private constructor. For example, there is no reason to create an instance from the Math class, because all of its data fields and methods are static. To prevent the user from creating objects from the Math class, the constructor in java.lang.Math is defined as follows:

private Math() {
}

Top comments (0)