protected
MembersChapter 10 discussed access modifiers public
and private
. A class’s public
members are accessible wherever the app has a reference to an object of that class or one of its derived classes. A class’s private
members are accessible only within the class itself. A base class’s private
members are inherited by its derived classes, but are not directly accessible by derived-class methods and properties. In this section, we introduce access modifier protected
. Using protected
access offers an intermediate level of access between public
and private
. A base class’s protected
members can be accessed by members of that base class and by members of its derived classes, but not by clients of the class.
All non-private
base-class members retain their original access modifier when they become members of the derived class—public
members of the base class become public
members of the derived class, and protected
members of the base class become protected
members of the derived class. Derived-class methods can refer to public
and protected
members inherited from the base class simply by using the member names. When a derived-class method overrides a base-class method, the base-class version can be accessed from the derived class by preceding the base-class method name with the keyword base
and the member access (.
) operator. We discuss accessing overridden members of the base class in Section 11.4.
Properties and methods of a derived class cannot directly access private
members of the base class. A derived class can change the state of private
base-class fields only through non-private
methods and properties provided in the base class.
Declaring private
fields in a base class helps you test, debug and correctly modify systems. If a derived class could access its base class’s private
fields, classes that inherit from that derived class could access the fields as well. This would propagate access to what should be private
fields, and the benefits of information hiding would be lost.