上QQ阅读APP看书,第一时间看更新
Specialist classes
Now for the three types of specialist classes, all derived from the Person base class:
class Infant extends Person { constructor(dateOfBirth: Date) { super(dateOfBirth); this.Category = PersonCategory.Infant; } canSignContracts(): boolean { return false; } } class Child extends Person { constructor(dateOfBirth: Date) { super(dateOfBirth); this.Category = PersonCategory.Child; } canSignContracts(): boolean { return false; } } class Adult extends Person { constructor(dateOfBirth: Date) { super(dateOfBirth); this.Category = PersonCategory.Adult; } canSignContracts(): boolean { return true; } }
Each of these classes uses inheritance to extend the Person class. As the DateOfBirth property has been declared as private, and is therefore only visible to the Person class itself, we must pass it down to the Person class in each of our constructors. Each constructor also sets the Category property based on the class type. Finally, each class implements the abstract function canSignContracts.
One of the benefits of using inheritance in this way is that the definitions of the actual classes become very simple. In essence, our classes are only doing two things—setting the Category property correctly, and defining whether or not they can sign contracts.