Public vs Private vs Protected — What's the Difference?
These access modifiers control which code can access a class's fields and methods: public members are accessible from anywhere, private members only from within the same class, and protected members from the class and its subclasses.
Published October 4, 2026
Access modifiers control who can use a class member: public is accessible everywhere, protected is accessible in the class and its subclasses, and private only inside the class itself.
The concept
They enforce encapsulation: expose a small public interface and hide the rest so internals can change safely.
Details vary slightly by language (Java also has package-private; Python uses naming conventions), but the three-level idea is common.
Who can see what
Practical examples
PHP
class Account {
public function deposit(int $n) { $this->balance += $n; }
protected function audit() {}
private int $balance = 0;
}TypeScript
class A { public a = 1; protected b = 2; private c = 3 }
class B extends A { f() { return this.b } }Java
private final String id;
protected void log() {}
public String getId() { return id; }Common mistakes
- Making everything public.
- Using protected for data that should be accessed through methods.
- Assuming TypeScript private is enforced at runtime (use #field for that).
Key takeaways
- public = everyone, protected = family, private = me.
- Hide internals behind methods.
- Start private, open up only when needed.
FAQ
What is package-private?
Java's default: visible within the same package.
How does Python do it?
By convention: _name is internal and __name is name-mangled.