Java Access Modifiers

Access modifiers control where a class member can be accessed from.

Java provides four access levels:

We will use simple Java files like:

User.java
UserService.java
Admin.java
Main.java

For package-related examples, we can simply mention the package at the top of the file.


1. private

A private member can only be accessed inside the same class.

User.java

class User {

    private String password = "secret123";

    void printPassword() {
        System.out.println(password); // ✅ Allowed
    }
}

The password variable is accessible inside User.

But another class cannot access it.

Main.java

class Main {

    public static void main(String[] args) {

        User user = new User();

        System.out.println(user.password); // ❌ Error
    }
}

Why?