Chapter 6. abstract classes and interfaces: Serious Polymorphism


A superclass inheritance hierarchy is just the beginning.

If you want to fully exploit polymorphism , you need to design using abstract classes and interfaces. In this chapter, you’ll discover how to use abstract classes to control which classes in your hierarchy can and can’t be instantiated . You’ll see how they can force concrete subclasses to provide their own implementations . You’ll find out how to use interfaces to share behavior between independent classes . And along the way, you’ll learn the ins and outs of is , as,  and when .

The Animal class hierarchy revisited

In the previous chapter, you learned how to design an inheritance hierarchy by creating the class structure for a bunch of animals. We abstracted out the common properties and functions into an Animal superclass, and overrode some of the properties and functions in the Animal subclasses so that we’d have subclass-specific implementations where we thought it was appropriate.

By defining the common properties and functions in the Animal superclass, we’re establishing a common protocol for all Animals, which makes the design nice and flexible. We can write code using Animal variables and parameters so that any Animal subtype (including ones we didn’t know about at the time we wrote our code) can be used at runtime.

Here’s a reminder of the class ...

Get Head First Kotlin now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.