Inheritance -Visibility Modifier

Java has four ways of controlling access to fields, methods, and classes. These modifiers, taken in increasing order of protection or visibility are:

  • private – the highest level of protection.
  • No modifier at all – has weak level of protection with respect to the modifier private.
  • protected – a weaker protection than no modifier.
  • public – the weakest level of protection.

You have already encountered private modifier and public modifier. You use the private modifier to hide members of a class. This means that these members can only be accessed from inside the class, and cannot be accessed directly from outside the class.

You use no modifier to allow direct access to classes and members of classes that are inside the same package, but not from outside packages. This is also known as package level modifier.

You use the protected modifier to allow the members of a class to be accessed by the subclasses or classes in the same package.

You use the public modifier to allow access to class and class members from anywhere, hence the word public.

A subclass can override a protected method in its superclass and change its visibility from protected to public. However, a subclass cannot change a public modifier to a protected modifier. In other words, a subclass cannot weaken the accessibility of a method defined in its superclass. It is for this reason why when you redefine the toString() method you must write the method signature in full. That is, you must write as:

public String toString() { … }

The method cannot be prefaced with either the modifier private or protected; neither can it be left at package level since these have narrower scope than public.

Figure 10.10 summarizes the accessibility of the members in a class.

Visibility Rules

Figure 10.10

Figure 10.10

Visibility modifiers are used to control how data and methods are accessed.

  • private modifier does not allow visibility outside of the class. Hence you should use methods with public modifier to provide access.
  • No specified modifier allows the members of the class to be accessed directly from any class within the same package but not from other packages.
  • The protected modifier enables the members of the class to be accessed by the subclasses in any package or classes in the same package.
  • The public modifier to enable the members of the class to be accessed by any class.

A subclass may override a protected method in its superclass and change its visibility to public. However, a subclass cannot weaken the accessibility of a method defined in the superclass.

1