Free mag vol1 | Page 287

CHAPTER 6  UNDERSTANDING INHERITANCE AND POLYMORPHISM  Note Although protected field data can break encapsulation, it is quite safe (and useful) to define protected methods. When building class hierarchies, it is very common to define a set of methods that are only for use by derived types and are not intended for use by the outside world. Adding a Sealed Class Recall that a sealed class cannot be extended by other classes. As mentioned, this technique is most often used when you are designing a utility class. However, when building class hierarchies, you might find that a certain branch in the inheritance chain should be “capped off,” as it makes no sense to further extend the linage. For example, assume you have added yet another class to your program (PTSalesPerson) that extends the existing SalesPerson type. Figure 6-4 shows the current update. Figure 6-4. The PTSalesPerson class PTSalesPerson is a class representing, of course, a part-time salesperson. For the sake of argument, let’s say that you want to ensure that no other developer is able to subclass from PTSalesPerson. (After all, how much more part-time can you get than “part-time”?) Again, to prevent others from extending a class, make use of the sealed keyword: sealed class PTSalesPerson : SalesPerson { public PTSalesPerson(string fullName, int age, int empID, float currPay, string ssn, int numbOfSales) :base (fullName, age, empID, currPay, ssn, numbOfSales) { } // Assume other members here... } 224