Sub topic 9
One Class, Many Interfaces
In Java, a class can extend only one parent class. It can implement many interfaces, though. An interface is a list of methods that a class promises to provide. A class can make several promises at once, so it can play several roles.
Why this matters
Think of a person who is both a cook and a driver. In the kitchen, people care only about cooking. In the car, people care only about driving. It is the same person, seen through a different role each time.
Java objects work this way too. One object can be "something you can draw" and also "something you can resize." Each part of your program uses only the role it needs.
The syntax
You list the interfaces after the implements keyword and separate them with commas:
class Square implements Drawable, Resizable {
// must provide every method from both interfaces
}The class must give a body to every abstract method in every interface it lists. If it skips even one method, the code will not compile.
A worked example
interface Drawable {
void draw();
}
interface Resizable {
void resize(double factor);
}
class Square implements Drawable, Resizable {
private double side;
Square(double side) {
this.side = side;
}
@Override
public void draw() {
System.out.println("Square of side " + side);
}
@Override
public void resize(double factor) {
side *= factor;
}
}
public class Main {
public static void main(String[] args) {
Square sq = new Square(3.0);
Resizable r = sq;
r.resize(2.0);
Drawable d = sq;
d.draw(); // prints: Square of side 6.0
}
}Here is what happens, step by step:
- We create one
Squareobject with side 3.0. - A reference is a variable that points to an object.
ris aResizablereference to the square, and it can call onlyresize. dis aDrawablereference to the same square, and it can call onlydraw.- Both references point to one object. The resize through
rchanged the side to 6.0, sod.draw()prints6.0.
What each reference can see
| Reference type | Methods you can call |
|---|---|
| `Square` | `draw()`, `resize()` |
| `Drawable` | `draw()` only |
| `Resizable` | `resize()` only |
The reference type limits what you can call. The object itself does not change.
Exercises
Exercise
Add a third interface, Named, with a method String name();. Make Square implement it and return "Square". What does the class header look like?
Show answer
class Square implements Drawable, Resizable, Named. Square must also add @Override public String name() { return "Square"; }.
Exercise
With Drawable d = sq;, can you write d.resize(2.0);? Why or why not?
Show answer
No. The Drawable type declares only draw(), so the compiler does not allow calling resize through d, even though the object really is a Square.