Understanding Java Access Modifiers: public, private, protected, and Package-Private

Java provides four access modifiers to control the visibility of classes, methods, and fields. These modifiers are public, private, protected, and the default (package-private) when no modifier is specified. Each defines a different level of access.

1. public

  • Visibility: Accessible from any other class in any package.
  • Applicable to: Classes, interfaces, methods, and fields.
  • Example:
public class Example {
    public int publicField;
    public void publicMethod() { }
}

2. private

  • Visibility: Accessible only within the same class.
  • Applicable to: Methods, fields, and inner classses (but not top-level classes).
  • Example:
public class Example {
    private int privateField;
    private void privateMethod() { }
}

3. protected

  • Visibility: Accessible within the same package and by subclasses (evenif they are in different packages).
  • Applicable to: Methods, fields, and inner classes (but not top-level classes).
  • Example:
public class Example {
    protected int protectedField;
    protected void protectedMethod() { }
}

4. Default (Package-Private)

  • Visibility: Accessible only within the same package (no explicit modifier).
  • Applicable to: Classes, interfaces (except nested), methods, and fields.
  • Example:
class Example {
    int defaultField;
    void defaultMethod() { }
}

Summary Table

Modifier Same Class Same Package Subclass (different package) Any class
public Yes Yes Yes Yes
protected Yes Yes Yes No
Default Yes Yes No No
private Yes No No No

Choosing the correct access modifier helps enforce encapsulation, reduces unintended dependencies, and clarifies the intended usage of your API.

Tags: java Access Modifiers public private protected

Posted on Sat, 05 Sep 2026 16:28:35 +0000 by billthrill