Access Modifiers in Java

Access modifiers control where a class, field, or method can be accessed.

1. Access Levels

Modifier Same Class Same Package Subclass in Other Package Everywhere
private Yes No No No
no modifier Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes

Easy way to remember

private
   ↓
same class only

default
   ↓
same package

protected
   ↓
same package + subclasses

public
   ↓
everywhere

2. public

Accessible from anywhere.

public class Dog {

    public void bark() {
        System.out.println("Woof!");
    }
}

A public top-level class can be used by classes in other packages.


3. Default / Package-Private

When no access modifier is specified, the member is package-private.

class Dog {

    void bark() {
        System.out.println("Woof!");
    }
}

Accessible only within the same package.

default is commonly called package-private. It is not written as default.


4. private

Accessible only inside its own class.

class Dog {

    private String name;

    private void bark() {
        System.out.println("Woof!");
    }
}

Other classes cannot directly access name or bark().


5. protected

Accessible:

class Animal {

    protected void eat() {
        System.out.println("Eating...");
    }
}

A subclass can access it:

class Dog extends Animal {

    void test() {
        eat();
    }
}

Choosing Access Modifiers

General rule

Use the most restrictive access level that makes sense.

Usually:

private → preferred
protected/default → when needed
public → only when necessary

Avoid public fields

Prefer:

class Person {
    private String name;
}

instead of:

class Person {
    public String name;
}

private fields give you better encapsulation and allow you to change the internal implementation later without affecting other classes.

Important

Use private by default unless you have a good reason to expose something.

Public fields are generally avoided, except for things such as constants.

Is a top-level class required to be public to run a Java file?