JAVA ACCESS MODIFIER
Modifier | Same Class | Same Package | Subclass (diff pkg) | Everywhere |
public | β
Yes | β
Yes | β
Yes | β
Yes |
protected | β
Yes | β
Yes | β
Yes | β No |
default (no modifier) | β
Yes | β
Yes | β No | β No |
private | β
Yes | β No | β No | β No |
π Explanation with Examples
1. public
- Visible everywhere.
- Best when you want your API accessible globally.
public class A { public int x = 10; public void show() { System.out.println("Public method"); } }
β
Accessible in same class, package, subclass, and different package.
new A().show();
2. private
- Visible only inside the same class.
- No one else (not even subclasses) can touch it.
public class A { private int secret = 42; private void hidden() { System.out.println("Private method"); } }
β Canβt be accessed outside A. Even if B extends A, it cannot access secret.
3. protected
- Visible in:
- Same class β
- Same package β
- Subclasses in other packages β
- But not visible in non-subclass classes of other packages.
package pkg1; public class A { protected int y = 20; protected void greet() { System.out.println("Protected method"); } }
- From pkg1.B (same package): β Allowed
- From pkg2.C extends A: β Allowed
- From pkg2.D (non-subclass): β Not Allowed
4. default (package-private)
- When you donβt write anything (no public, no private, no protected).
- Visible only in the same package.
class A { // π no modifier β package-private void hello() { System.out.println("Default access"); } }
- From pkg1.B: β Allowed
- From pkg2.C: β Not Allowed
β‘ Quick Real-world Mapping
- public β Open door, anyone can come in.
- private β Locked in your room, only you can access.
- protected β Family (subclasses + same package) can access.
- default β Friends in the same neighborhood (package) can access.
Β
Β
-Concept-in-Java.webp?table=block&id=266e1a6f-db0e-8015-b58e-df07daf62e17&cache=v2)