Free mag vol1 | Page 286

CHAPTER 6  UNDERSTANDING INHERITANCE AND POLYMORPHISM Finally, recall that once you add a custom constructor to a class definition, the default constructor is silently removed. Therefore, be sure to redefine the default constructor for the SalesPerson and Manager types. For example: // Add back the default ctor // in the Manager class as well. public SalesPerson() {} Keeping Family Secrets: The protected Keyword As you already know, public items are directly accessible from anywhere, while private items can only be accessed by the class that has defined them. Recall from Chapter 5 that C# takes the lead of many other modern object languages and provides an additional keyword to define member accessibility: protected. When a base class defines protected data or protected members, it establishes a set of items that can be accessed directly by any descendent. If you want to allow the SalesPerson and Manager child classes to directly access the data sector defined by Employee, you can update the original Employee class definition as follows: // Protected state data. partial class Employee { // Derived classes can now directly access this information. protected string empName; protected int empID; protected float currPay; protected int empAge; protected string empSSN; ... } The benefit of defining protected members in a base class is that derived types no longer have to access the data indirectly using public methods or properties. The possible downfall, of course, is that when a derived type has direct access to its parent’s internal data, it is very possible to accidentally bypass existing business rules found within public properties. When you define protected members, you are creating a level of trust between the parent and child class, as the compiler will not catch any violation of your type’s business rules. Finally, understand that as far as the object user is concerned, protected data is regarded as private (as the user is “outside” of the family). Therefore, the following is illegal: static void Main(string[] args) { // Error! Can't access protected data from object instance. Employee emp = new Employee(); emp.empName = "Fred"; } 223