DEV Community

ViGnEsH
ViGnEsH

Posted on

Access Modifier. When to Use and When Not to Use for class, method, variable, and constructors.

July 14 2026

Access modifiers Definition :

  • Access modifiers in Java are keywords that control the visibility and accessibility of classes, methods, variables, and constructors.
  • They play a fundamental role in enforcing encapsulation (data hiding).

There are four types of Access modifiers

1. Private

  • The private access modifier in Java .
  • Members marked as private can only be accessed within the exact same class where they are declared.


2. Default (Package-Private)

  • When you do not specify an explicit access modifier, Java automatically applies the default access level.
  • Components are accessible only by classes residing in the same package.


3. Protected

  • Accessible within the same class, package, and subclasses.
  • Also, access different package subclasses (Child class)
  • Cannot allow a different package non-subclass


4. Public

  • Components are accessible from anywhere in the program

https://www.sitesbay.com/java/images/access-modifiers-in-java.png


When to Use and When Not to Use for class, method, variable, and constructors.

Key Points

  • Access Modifiers for Classes

  • public Accessible from anywhere.

  • Default (no modifier) Accessible only within the same package.

  • Private and protected cannot be used with top-level classes.


  • Access Modifiers for method

  • public Accessible from anywhere.

  • protected Accessible within the same package and by subclasses in other packages.

  • Default (no modifier) Accessible only within the same package.

  • private Accessible only within the same class.


  • Access Modifiers for variables

  • public Accessible from anywhere.

  • protected Accessible within the same package and by subclasses in other packages.

  • Default (no modifier) Accessible only within the same package.

  • private Accessible only within the same class.


  • *Access Modifiers for Constructors *

  • public The constructor can be called from anywhere.

  • protected Constructor can be called within the same package and by subclasses in other packages.

  • Default (no modifier) Constructor can be called only within the same package.

  • private → Constructor can be called only within the same class.

Top comments (0)