7.3 Interfaces Extending Classes

When an interface type extends a class type it inherits the members of the class but not their implementations. It is as if the interface had declared all of the members of the class without providing an implementation. Interfaces inherit even the private and protected members of a base class. When a class containing private or protected members is the base type of an interface type, that interface type can only be implemented by that class or a descendant class. For example:

  1. class Control {
  2. private state: any;
  3. }
  4. interface SelectableControl extends Control {
  5. select(): void;
  6. }
  7. class Button extends Control {
  8. select() { }
  9. }
  10. class TextBox extends Control {
  11. select() { }
  12. }
  13. class Image extends Control {
  14. }
  15. class Location {
  16. select() { }
  17. }

In the above example, ‘SelectableControl’ contains all of the members of ‘Control’, including the private ‘state’ property. Since ‘state’ is a private member it is only possible for descendants of ‘Control’ to implement ‘SelectableControl’. This is because only descendants of ‘Control’ will have a ‘state’ private member that originates in the same declaration, which is a requirement for private members to be compatible (section 3.11).

Within the ‘Control’ class it is possible to access the ‘state’ private member through an instance of ‘SelectableControl’. Effectively, a ‘SelectableControl’ acts like a ‘Control’ that is known to have a ‘select’ method. The ‘Button’ and ‘TextBox’ classes are subtypes of ‘SelectableControl’ (because they both inherit from ‘Control’ and have a ‘select’ method), but the ‘Image’ and ‘Location’ classes are not.