Access Modifiers in Java and its scope?

In Java, access modifiers determine the visibility or accessibility of classes, methods, constructors, and variables. They help enforce encapsulation and control how different parts of your code interact.

There are four main access modifiers in Java:

1. public

  • Scope: Accessible from anywhere in the program—across all packages.
  • Use Case: When you want a class or method to be universally accessible.
  • Example:

2. protected

  • Scope:
    • Accessible within the same package.
    • Also accessible in subclasses, even if they are in different packages.
  • Use Case: When you want to allow inheritance but still restrict access to outsiders.
  • Example:

3. default (no modifier)

  • Scope: Accessible only within the same package.
  • Use Case: When you want to hide implementation details from other packages.
  • Example:

4. private

  • Scope: Accessible only within the same class.
  • Use Case: When you want to encapsulate logic or data completely.
  • Example:

🔒 Summary Table

ModifierSame ClassSame PackageSubclass (Other Package)Other Packages
public
protected
default
private

Leave a Reply

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