JAVA OOPS & Stream
πŸš€

JAVA OOPS & Stream

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.
Β 
Β 

Java Stram APIs

Built with Potion.so