Access modifiers control the visibility of class members, enforcing encapsulation by restricting who can read or call them.
Access modifiers control the visibility of class members, enforcing encapsulation by restricting who can read or call them.
| Modifier | Accessible from |
|---|
public | Anywhere |
protected | The class and its subclasses |
private | Only within the declaring class |
public class Employee {
private double salary; // internal — only Employee touches it
protected String department; // subclasses may use it
public String name; // open to all
public double getSalary() { // controlled, public read access
return salary;
}
}
salary is private so no outside code can corrupt it; the public getter is the only window in.
class Demo:
def __init__(self):
self.public = 1
self._protected = 2 # convention only ("don't touch")
self.__private = 3 # name-mangled to _Demo__private
Python has no enforced private — it relies on naming conventions. Java/C# enforce modifiers at compile time. Java also has package-private (the default, no keyword).
Making everything public defeats encapsulation. Default to the most restrictive level and widen only when a real need appears.
Access modifiers are the concrete tool that turns encapsulation from a principle into an enforced rule the compiler checks.
A small public surface area means less code can depend on internals, so you can refactor freely without breaking callers.