Interfaces and Polymorphism
In the last chapter we discussed the pillar of abstraction. Creating abstract classes is widely recognized as one method of achieving abstraction. An interface is another construct/tool that help us in our goal of achieving abstraction. Not all object-oriented languages have an interface construct, but many do. While Java was not the first OOP language to use the interface keyword, it is the language that made it popular. In this chapter we will discuss what a Java interface is and how it is used. In short, an interface is like a 100% abstract class. Meaning, an interface cannot have any implementation code (method bodies) in it.
Updated
What is an Interface?
- Interface Definition (Apprentice): The word "interface" is both a noun and a verb, and software uses both meanings.
- User Interfaces (Novice): A smart home's thermostat, wall panel, phone app and voice assistant show how many user interfaces can control the same software.
- Software Interfaces (Apprentice): A software interface is a contract that defines how one piece of code can interact with another.
Abstraction through Interfaces
- Solving Multiple Inheritance (Journeyman): Java allows only one parent class, so interfaces let a class take on more than one set of abilities without the problems of multiple inheritance.
Defining Interfaces
- Defining Interfaces (Journeyman): How to write a Java interface and implement more than one in a class with the `implements` keyword.
What is Polymorphism
- What is Polymorphism: an overview (Journeyman): Polymorphism means "many forms": one object can play many roles, like a teenager who is a student, a singer and an athlete.
- Changing Roles (Journeyman): Polymorphism means focusing on just the one role of an object that matters at the moment, as Chloe is a student, a musician and an athlete at different times of day.
- Polymorphism with Interfaces (Freelancer): Using an interface as a variable's type lets you treat an object as just one of its roles, such as treating a Teenager as a Student or a team as a list of Athletes.