protected Members

Chapter 9 discussed access modifiers public, private, and internal. A class's public members are accessible wherever the application 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. (Members of a class can also be declared protected internal. A base class's protected internal members can be accessed by members of that base class, by members of its derived classes and by any class in the same assembly.)

All non-private base class members retain their original access modifier when they become members of the derived class (i.e., 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 of the method can be accessed from the derived class by preceding the base class method name with the keyword base and the dot (.) operator. We discuss accessing overridden members of the base class in Section 10.4.

Software Engineering Observation 10 1

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.

Software Engineering Observation 10 2

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 base 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.

Relationship between Base Classes and Derived Classes

Категории