Interfaces
Besides inheritance, through which you can create is-a relationships, there is another way to define abstractions. You can also create and implement interfaces that define has-a relationships. Interfaces are most commonly described as contracts.
They only contain (public) method signatures (that is, method names, inputs, and outputs) and (public) constants. When a piece of code implements an interface, it is forced to respect the contract and to implement each and every method of the interface. Otherwise, the contract is not properly implemented (and the compiler will not be happy), unless it is an abstract class.
If we continue with our Car analogy, you could define an Engine interface with the startEngine and stopEngine methods. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access