Free mag vol1 | Page 295

CHAPTER 6  UNDERSTANDING INHERITANCE AND POLYMORPHISM When you select a member and hit the Enter key, the IDE responds by automatically filling in the method stub on your behalf. Note that you also receive a code statement that calls your parent’s version of the virtual member (you are free to delete this line if it is not required). For example, if you used this technique when overriding the DisplayStats() method, you might find the following autogenerated code: public override void DisplayStats() { base.DisplayStats(); } Sealing Virtual Members Recall that the sealed keyword can be applied to a class type to prevent other types from extending its behavior via inheritance. As you might remember, you sealed PTSalesPerson as you assumed it made no sense for other developers to extend this line of inheritance any further. On a related note, sometimes you might not wish to seal an entire class, but simply want to prevent derived types from overriding particular virtual methods. For example, assume you do not want parttime salespeople to obtain customized bonuses. To prevent the PTSalesPerson class from overriding the virtual GiveBonus() method, you could effectively seal this method in the SalesPerson class as follows: // SalesPerson has sealed the GiveBonus() method! class SalesPerson : Employee { ... public override sealed void GiveBonus(float amount) { ... } } Here, SalesPerson has indeed overridden the virtual GiveBonus() method defined in the Employee class; however, it has explicitly marked it as sealed. Thus, if you attempted to override this method in the PTSalesPerson class, you receive compile-time errors, as shown in the following code: 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) { } // Compiler error! Can't override this method // in the PTSalesPerson class, as it was sealed. public override void GiveBonus(float amount) { } } 232