Inheritance, Interfaces and Polymorphism
Learn how one class can extend another, how interfaces define what a type can do, and how polymorphism lets one loop treat many kinds of objects, with real output and call counts.
In this lesson you will
- Extend a class and override a method
- Define and implement an interface
- Use polymorphism in one loop
- Choose between inheritance and interfaces
About 28 minutes
Bikes, scooters and helmets
Hana starts renting scooters and helmets next to bikes. Each item has a name and a price, but the way the price is worked out differs: bikes charge per day, scooters per hour with a minimum, and helmets cost a flat fee. She wants one invoice loop that handles all of them, without a chain of if statements that asks what kind each item is. Object-oriented design gives two tools: inheritance and interfaces.
Inheritance lets a class extend another and reuse its fields and methods, written class Scooter extends Item. The subclass may override a method to change its behaviour, and the annotation @Override asks the compiler to check that you really override something. An abstract class cannot be created directly and may declare abstract methods that subclasses must fill in. An interface describes what a type can do, as a list of methods, without storing data, and a class can implement many interfaces but extend only one class. Polymorphism means that a variable of the general type can hold any specific one, and the call runs the version that belongs to the actual object.
| Tool | Use it for | Limit |
|---|---|---|
| extends | Sharing code and data in an is-a relationship | One parent class only |
| abstract class | A base that needs subclasses to complete it | Cannot be instantiated |
| interface | A role or ability, such as Rentable | No instance data |
| @Override | Marking an override so the compiler checks it |
import java.util.*;
interface Describable { String describe(); }
abstract class Item implements Describable {
protected final String name;
static int priceCalls = 0;
Item(String name) { this.name = name; }
abstract int price(int units);
int quote(int units) { priceCalls++; return price(units); }
public String describe() { return name + " [" + getClass().getSimpleName() + "]"; }
}
class Bike extends Item {
Bike(String n) { super(n); }
int price(int days) { return days * 1200; }
}
class Scooter extends Item {
Scooter(String n) { super(n); }
int price(int hours) { return Math.max(hours, 2) * 500; }
@Override public String describe() { return super.describe() + " per hour, minimum 2"; }
}
class Helmet extends Item {
Helmet(String n) { super(n); }
int price(int ignored) { return 300; }
}
public class Main {
public static void main(String[] args) {
List<Item> items = List.of(new Bike("City 1"), new Scooter("Zip 7"), new Helmet("Helmet M"), new Scooter("Zip 8"));
int[] units = {3, 1, 1, 6};
int total = 0;
for (int i = 0; i < items.size(); i++) {
Item it = items.get(i);
int p = it.quote(units[i]);
total += p;
System.out.println(it.describe() + " x" + units[i] + " = " + p);
}
System.out.println("total: " + total + " cents, quotes computed: " + Item.priceCalls);
Describable d = items.get(1);
System.out.println("an Item is Describable: " + (items.get(0) instanceof Describable) + ", Scooter is an Item: " + (d instanceof Item));
if (d instanceof Scooter s) System.out.println("pattern match gives a Scooter named " + s.name);
}
}
City 1 [Bike] x3 = 3600
Zip 7 [Scooter] per hour, minimum 2 x1 = 1000
Helmet M [Helmet] x1 = 300
Zip 8 [Scooter] per hour, minimum 2 x6 = 3000
total: 7900 cents, quotes computed: 4
an Item is Describable: true, Scooter is an Item: true
pattern match gives a Scooter named Zip 7
One loop priced four different kinds of item, and the line for each used the right rule: three bike days cost 3600 cents, one scooter hour was raised to the two-hour minimum, so it cost 1000, the helmet cost a flat 300 and the six-hour scooter cost 3000. The total is 7900 cents and the counter shows that 4 quotes were computed, one per item, from a single call, it.quote, in the loop. The loop never asks what kind of object it has. Java chooses the method at run time from the real class of the object, which is called dynamic dispatch.
The Scooter overrides describe and calls super.describe() to reuse the parent’s text before adding its own. The Helmet ignores its units parameter, which shows a weakness of this simple design that a more careful model would fix. The last lines use instanceof: the check on a variable typed Describable tells us that the first item is describable and the second an Item, and the pattern match “d instanceof Scooter s” both tests and declares a variable of the specific type in one step.
Check by hand: 3 x 1200 = 3600; max(1, 2) x 500 = 1000; 300; 6 x 500 = 3000. The sum is 3600 + 1000 + 300 + 3000 = 7900, matching the program.
Inheritance says “is a”. A Scooter is an Item, but a Rental is not a Bike. If the relationship is “has a”, store an object in a field instead, which is called composition.
Declare variables and parameters with the interface or base type, such as List or Describable, so that you can swap implementations without changing the rest of the code.
Every program in this lesson was compiled and run with OpenJDK 21 while the course was written. Java releases twice a year, so check the official Java documentation for the current version and for features added after Java 21.
Practice
Add a Trailer item with a daily price and a deposit. Add a method to the Describable interface with a default implementation, using the default keyword, and see that existing classes keep working. Then write a short note about which relationships in the model are is-a and which are has-a.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does @Override do?
- Hides a method
- Asks the compiler to check that a method overrides one
- Deletes a method
- Makes a method static
It catches typos in method names.
How many classes can a class extend?
- One
- Two
- As many as it likes
- None
But it can implement many interfaces.
What is polymorphism?
- One type reference running the right version for the actual object
- Having many files
- A kind of loop
- Two variables with one name
Dynamic dispatch.
Can you create an object of an abstract class directly?
- Yes
- Only with static
- Only in main
- No
You create a subclass object.
What does an interface contain?
- Only variables
- Only loops
- Only files
- Method declarations, without instance data
A class implements it.
Summary
- extends shares code in an is-a relationship; a class has one parent.
- Interfaces describe abilities and a class can implement many.
- Polymorphism runs the method of the real object.
- Prefer composition when the relationship is has-a.
Questions
What is the difference between abstract classes and interfaces?
An abstract class can hold fields and shared code, and a class extends only one. An interface describes abilities, and a class can implement several.
What is super?
A keyword that refers to the parent class, for calling its constructor or its methods.
Is deep inheritance a good idea?
Usually not. Deep hierarchies are hard to change. Prefer shallow ones and composition.
