Chapter 5. subclasses and superclasses: Using Your Inheritance
Ever found yourself thinking that an object’s type would be perfect if you could just change a few things?
Well, that’s one of the advantages of inheritance. Here, you’ll learn how to create subclasses, and inherit the properties and functions of a superclass. You’ll discover how to override functions and properties to make your classes behave the way you want, and you’ll find out when this is (and isn’t) appropriate. Finally, you’ll see how inheritance helps you avoid duplicate code, and how to improve your flexibility with polymorphism.
Inheritance helps you avoid duplicate code
When you develop larger applications with multiple classes, you need to start thinking about inheritance. When you design with inheritance, you put common code in one class, and then allow other more specific classes to inherit this code. When you need to modify the code, you only have to update it in one place, and the changes are reflected in all the classes that inherit that behavior.
The class that contains the common code is called the superclass, and the classes that inherit from it are called subclasses.
Note
A superclass is sometimes called a base class, and a subclass is sometimes called a derived class. In this book, we’re sticking with superclass and subclass.
An inheritance example
Suppose you have two classes named Car ...
Get Head First Kotlin now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.