What are the differences between public, protected, and private visibility, and how does protected behave differently in the context of inheritance?
Last updated
Visibility controls where a property or method can be accessed: public everywhere, protected within the class and its subclasses, and private only within the declaring class itself.
public: Accessible from anywhere: outside code, subclasses, and the class itself.protected: Accessible inside the declaring class and any class that extends it, but not from outside.private: Accessible only within the exact class that declared it, not even in subclasses.Inheritance distinction:
A
privatemember is invisible to children, so a subclass can declare its own member of the same name without conflict.A
protectedmember is shared and overridable down the hierarchy, making it the right choice for internal state subclasses must reach.