Access Modifiers in Java

🔑 What are Access Modifiers?

  • Access modifiers define the visibility or accessibility of classes, methods, and variables.
  • They control who can access what in your program.
  • Java has four main access modifiers:
ModifierClassPackageSubclassWorld (anywhere)
private
default
protected
public

“Default” access is when no modifier is specified.


🔑 1. Private

  • Accessible only within the same class.
  • Used to encapsulate data.
class Test {
    private int secret = 42;

    void showSecret() {
        System.out.println(secret);
    }
}

public class Main {
    public static void main(String[] args) {
        Test t = new Test();
        t.showSecret(); // OK
        // System.out.println(t.secret); // ❌ Compile error
    }
}

🔑 2. Default (Package-Private)

  • Accessible within the same package.
  • No keyword is used.
class Test {
    int number = 10; // default access
}

public class Main {
    public static void main(String[] args) {
        Test t = new Test();
        System.out.println(t.number); // OK if same package
    }
}

🔑 3. Protected

  • Accessible within the same package and subclasses (even in different packages).
package pkg1;
class Parent {
    protected int data = 50;
}

package pkg2;
import pkg1.Parent;

class Child extends Parent {
    void show() {
        System.out.println(data); // OK: protected accessed in subclass
    }
}

🔑 4. Public

  • Accessible from anywhere (any class, any package).
public class Test {
    public int number = 100;
}

public class Main {
    public static void main(String[] args) {
        Test t = new Test();
        System.out.println(t.number); // Accessible anywhere
    }
}

🔑 Quick Rules:

  1. Class Level → Can only be public or default.
  2. Members (fields & methods) → Can be private, default, protected, or public.
  3. Encapsulation tip → Make fields private and methods public (getter/setter).

Summary Table

ModifierClassPackageSubclassWorld
private
default
protected
public

Leave a Reply