Skip to main content

#TC201 #Topic10 What are visibility modifiers, their purpose and use in practice?

3 min read

Let's start with this chart: 

            | Class | Package | Subclass | World
public      |  y    |    y    |    y     |   y
protected   |  y    |    y    |    y     |   n
no modifier |  y    |    y    |    n     |   n
private     |  y    |    n    |    n     |   n

y: accessible
n: not accessible
  • private member is only accessible within the same class as it is declared.

  • A member with no access modifier is only accessible within classes in the same package.

  • protected member is accessible within all classes in the same package and within subclasses in other packages.

  • public member is accessible to all classes (unless it resides in a module that does not export the package it is declared in).



Which modifier to choose?

Access modifiers is a tool to help you to prevent accidentally breaking encapsulation(*). Ask yourself if you intend the member to be something that's internal to the class, package, class hierarchy or not internal at all, and choose access level accordingly.

Access Control and Inheritance:

The following rules for inherited methods are enforced:

  • Methods declared public in a superclass also must be public in all subclasses.

  • Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.

  • Methods declared private are not inherited at all, so there is no rule for them.




Access modifiers