Java Access Modifiers in a Nutshell

Java access modifiers control the visibility of classes, variables, methods, and other members of a Java program.

What are access modifiers in Java?

Access modifiers are used to specify the scope of access of the member variable and methods of a class from a different class or package. The accessibility scope varies based on the modifiers you use. There are four access modifiers in Java –

  • Default
  • Private
  • Protected
  • Public

Access Modifier Table

Access ModifierDefaultPrivateProtectedPublic
Same ClassYYYY
Same Package SubclassYNYY
Same Package Non-SubclassYNYY
Different Package SubclassNNYY
Different Package Non-SubclassNNNY

Description

  • You can access the Default, Private, Protected, and Public variables within the same class.
  • You can access the Default, Protected, and Public but not the private variables in the Same Package Subclass.
  • You can access the Default, Protected, and Public but not the private variables in the Same Package Non-Subclass.
  • You can access the Protected and Public variables but not the Default and Private variables in the Different Package Subclass.
  • You can access the Public variables but not the Default and Private and Protected variables in the Different Package Non-Subclass.

Explanation Video

A small video to explain the access modifiers in Java

Feel free to share your viewpoints on this topic in the comments section below 🙂

Spread the word!
0Shares

Leave a comment

Your email address will not be published. Required fields are marked *