Access Modifiers and Visibility
You'll learn how to control which parts of your code can see and use class members using access modifiers.
What Are Access Modifiers?
Access modifiers are keywords that define where in your codebase different members (variables and methods) of a class can be accessed. They're the gatekeepers of encapsulation, enforcing the boundaries you established when hiding information inside classes.
Think of a house: some rooms are public (anyone can enter), some are private (family only), and some are protected (family and close relatives). Access modifiers work the same way for class members.
The Three Core Modifiers
public: The member is visible everywhere—inside the class, outside the class, in subclasses, anywhere in your program. Use this for the intentional interface you want others to use.
private: The member is visible only within the defining class. No outside code—not even subclasses—can access it directly. Use this for internal implementation details you want to hide completely.
protected: The member is visible within the defining class and its subclasses, but not to unrelated code. This creates a middle ground for inheritance hierarchies.
Why It Matters
By choosing the right access modifier, you enforce encapsulation boundaries. You can change private implementation details without breaking external code, because that code never had access anyway. You expose only what's necessary through public members, maintaining a clean contract with users of your class.
Key Takeaway: Access modifiers (public, private, protected) control visibility of class members, enforcing encapsulation by restricting where those members can be accessed and preventing unwanted coupling between code components.