Java Access Modifiers

Access modifiers are the collective name for modifiers such as public, protected, and private. They determine where a class or its members can be accessed from.

Access Modifiers

Access modifier Overview
public Accessible from all classes.
protected Accessible from the current class and subclasses.
None (default) Accessible from classes in the same package as the current class.
private Accessible only from the current class.

The state where an access modifier is omitted is called package private, meaning that access is freely allowed only within the package.

For example, the following code lets you check the behavior of each access level.

package com.devkuma.basic.modifier;

public class ModAccess {
    public String pubVar = "public";
    protected String protVar = "protected";
    String packVar = "package private";
    private String priVar = "private";

    public void test() {
        // Inside the class, members of all levels can be accessed.
        System.out.println(this.pubVar);
        System.out.println(this.protVar);
        System.out.println(this.packVar);
        System.out.println(this.priVar);
    }

    public static void main(String[] args) {
        ModAccess m = new ModAccess();
        m.test();
    }
}

Execution result:

public
protected
package private
private

The class below is a subclass of ModAccess.

package com.devkuma.basic.modifier;

// Subclass of ModAccess
public class ModAccessChild extends ModAccess {

    public void test() {
        System.out.println(this.pubVar);
        System.out.println(this.protVar);
        System.out.println(this.packVar);
        // System.out.println(this.priVar); // private variables cannot be accessed.
    }

    public static void main(String[] args) {
        ModAccess mc = new ModAccessChild();
        mc.test();
    }
}

Execution result:

public
protected
package private

The class below is in a different package and has no inheritance relationship with ModAccess.

package com.devkuma.basic.modifier.other;

import com.devkuma.basic.modifier.ModAccess;

// A different package class with no inheritance relationship to ModAccess
public class ModAccessOther {
    public static void main(String[] args) {
        ModAccess my = new ModAccess();
        System.out.println(my.pubVar);
        // Members at protected level or below cannot be accessed.
        // System.out.println(my.protVar);
        // System.out.println(my.packVar);
        // System.out.println(my.priVar);
    }
}

Execution result:

public

The rule for specifying access modifiers is simply to make the access range as narrow as possible while still satisfying the requirements.

In particular, there is a big difference between package private and public/protected. Package private and private mean that the API is not public, so compatibility does not need to be considered as strongly when modifying code. However, public and protected are public APIs, so care is required for users.