JAVA - Zero to Hero / Object Oriented Programming (OOP)

Access Modifiers

❔ What Are Access Modifiers?

  • Access modifiers in Java control the visibility (access level) of classes, methods, and variables.

  • They help with security, encapsulation, and code organization.

🔐 Types of Access Modifiers

Modifier

Accessible Within Class

Within Package

Subclass in Other Package

Other Packages

private

✅ Yes

❌ No

❌ No

❌ No

(default)

✅ Yes

✅ Yes

❌ No

❌ No

protected

✅ Yes

✅ Yes

✅ Yes

❌ No

public

✅ Yes

✅ Yes

✅ Yes

✅ Yes

🧠 If no modifier is specified, it's default/package-private.


🔐 private

  • Accessible only within the same class.

  • Best for data hiding and encapsulation.

class BankAccount {
    private int balance = 1000;

    public int getBalance() {
        return balance;
    }
}

❌ Can't be accessed from another class directly.


🔓 public

Accessible from anywhere — any class, any package.

public class Main {
    public static void main(String[] args) {
        System.out.println("This is public.");
    }
}

✅ Use it when you want methods/classes to be available everywhere.


📦 default (No modifier)

Accessible only within the same package.

class Message {
    void show() {
        System.out.println("Default access");
    }
}

❌ Not visible outside the package.


🛡️ protected

Accessible within the same package and in subclasses (even in different packages).

class Animal {
    protected void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    void bark() {
        sound();  // allowed due to protected
    }
}

✅ Used mainly when doing inheritance + controlled access.


Practical Example

class Demo {
    public int x = 1;
    private int y = 2;
    protected int z = 3;
    int w = 4;  // default

    public void printValues() {
        System.out.println(x + ", " + y + ", " + z + ", " + w);
    }
}

✅ All members are accessible within the same class

Outside class? Only x (public) and z (protected, if extended) may be accessible depending on the context.

👇 Outside Class Example: TestAccess.java

public class TestAccess {
    public static void main(String[] args) {
        Demo d = new Demo();
        System.out.println(d.x); // ✅ public — accessible
        // System.out.println(d.y); // ❌ private — not accessible
        System.out.println(d.z); // ✅ protected — accessible (same package)
        System.out.println(d.w); // ✅ default — accessible (same package)
    }
}
1
3
4

✅ Recap Table

Modifier

Scope

Use Case

private

Same class only

Hiding sensitive data

default

Same package only

Internal logic within a package

protected

Same package + subclasses in other pkgs

Controlled inheritance access

public

Everywhere

General utility, entry points