Java: public, private, protected


Access modifiers in Java are keywords that are used to specify the accessibility of fields, methods, constructors and classes. There are four access modifiers, each specifying a certain level of accessibility:

  1. public: can be accessed from anywhere

2. protected: can be accessed from within the class itself, the package and by subclasses

3. package-private (default): can be accessed within the class itself and the package only

4. private: can be accessed only within the class

Public access

Giving a field a public access modifier allows it to be accessed from anywhere. However, it is important to keep in mind that labelling fields in a class as public is considered to be bad practice so typically member in a Java class are given a private access modifier (in spirit of encapsulating those fields). Naturally, the only fields that will have a public access modifier are constants (fields that have a final modifier and therefore cannot be changed).

Classes are typically given a public access modifier and every file that contains a class can only have one public class. This public class also has to have the same name as the file name.

Protected access

Protected fields can only be accessed from within the class they are declared in and anywhere within the same package. Fields with the protected modifier are also accessible outside the package but only through inheritance.

Top level classes in Java cannot be given the protected access modifier.

Package-private (default access)

Not specifying an access modifier on a field grants it package-private accessibility, which the default access scope in Java. Package-private has the same access that a field with a protected modifier would have with one exception; subclasses won’t be able to access that field. Therefore, if a class inherits from a parent class that has a field with no access modifier; the subclass won’t have access to that field.

A class can have package-private accessibility but it’s access will be limited only within it’s own package.

Private access

Private fields can only be accessed from within the class they are declared in; this is the modifier that provides the least access in Java. Private fields are not inherited to subclasses and cannot be access anywhere outside the class.

Classes cannot be labelled private because it just does not make sense to do so; the class would not be able to interact with the rest of the program in any way.

Hope you learned something!




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store