Sub topic 9
One Class, Many Interfaces
In the last chapter, you programmed to an abstract type. You wrote code that talks to a Shape or a Drawable and does not care which class sits behind it. This chapter adds one more idea: a single class can make several promises at the same time.
A class in Java can extend only one class. It can implement as many interfaces as it needs. This is how Java lets one object fill several roles without the problems that come from inheriting code from many parents.
Why One Class Needs Several Roles
Think about a square on a drawing screen. The screen needs to draw it. A zoom tool needs to resize it. A save button may need to store it in a file. These are three separate jobs, and each one belongs to a different part of the program.
You could put all three methods into one big interface. That forces every class to support every job, even classes that cannot be resized. A better design splits each job into its own small interface. Each class then picks the interfaces that fit it.
A role here means one set of behavior that other code can rely on. Each interface describes one role.
The Syntax: A Comma-Separated List
To implement more than one interface, list them after implements, separated by commas. The class must then supply a body for every abstract method in every interface.
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
}
}Look at the main method. The variables r and d hold the same object, and only one Square exists. When r.resize(2.0) changes the side, d.draw() sees the change.
The Reference Type Controls What You Can Call
A reference type is the type you declare for a variable, such as Resizable r. It decides which methods the compiler lets you call. The object itself may be able to do more.
| Variable | Can call `draw()`? | Can call `resize()`? |
|---|---|---|
| `Square sq` | Yes | Yes |
| `Drawable d` | Yes | No |
| `Resizable r` | No | Yes |
If you write d.resize(2.0), the code will not compile, even though the object is a Square. The compiler only knows that d is a Drawable. This limit is useful. Code that receives a Drawable cannot accidentally resize anything.
Moving Between Roles
Sometimes you hold an object through one interface and need another role. You can check with instanceof, then cast. A cast tells the compiler to treat a reference as a different type.
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 {
static void zoomIfPossible(Drawable item) {
if (item instanceof Resizable) {
Resizable r = (Resizable) item;
r.resize(1.5);
}
item.draw();
}
public static void main(String[] args) {
zoomIfPossible(new Square(4.0)); // prints: Square of side 6.0
}
}The instanceof check protects you. If the object does not implement Resizable, a cast without the check would throw a ClassCastException while the program runs.
Extending a Class and Implementing Interfaces Together
A class can extend one class and implement many interfaces in the same declaration. The extends part must come first.
interface Drawable {
void draw();
}
interface Resizable {
void resize(double factor);
}
abstract class Shape {
private final String name;
protected Shape(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
class Circle extends Shape implements Drawable, Resizable {
private double radius;
Circle(double radius) {
super("Circle");
this.radius = radius;
}
@Override
public void draw() {
System.out.println(getName() + " of radius " + radius);
}
@Override
public void resize(double factor) {
radius *= factor;
}
}
public class Main {
static void growAll(Resizable[] items) {
for (Resizable item : items) {
item.resize(2.0);
}
}
public static void main(String[] args) {
Circle c = new Circle(1.0);
Resizable[] items = { c };
growAll(items);
c.draw(); // prints: Circle of radius 2.0
}
}Circle gets its name field and constructor from Shape. It gets its roles from the two interfaces. The method growAll works with any Resizable, so it would also accept a Square, even though Square and Circle share no parent class.
When Two Interfaces Ask for the Same Method
Two interfaces may declare the exact same abstract method. That is fine. One method body satisfies both.
interface Printer {
void start();
}
interface Scanner {
void start();
}
class OfficeMachine implements Printer, Scanner {
@Override
public void start() {
System.out.println("Machine warming up");
}
}
public class Main {
public static void main(String[] args) {
Printer p = new OfficeMachine();
Scanner s = new OfficeMachine();
p.start(); // prints: Machine warming up
s.start(); // prints: Machine warming up
}
}There is one trap. Suppose the methods have the same name and parameters but different return types, such as int size() in one interface and long size() in the other. A class cannot satisfy both with one method, and it cannot have two methods that differ only by return type. The class will not compile.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| Forgetting one interface's method | Compile error: class is not abstract and does not override the method | Add the missing method |
| Leaving out `public` | Compile error about weaker access | Mark the method `public` |
| Writing `implements` before `extends` | Syntax error | Put `extends` first |
| Calling a method the reference type lacks | Compile error: cannot find symbol | Use a reference of the right interface |
| Casting without `instanceof` | `ClassCastException` at run time | Check with `instanceof` first |
Exercise
Write an interface Playable with void play() and an interface Rateable with int rating(). Write a class Song that implements both, returns a rating of 5, and prints "Playing song" from play(). In main, store one Song in a Playable variable and call play().
Show answer
interface Playable { void play(); } interface Rateable { int rating(); } class Song implements Playable, Rateable { @Override public void play() { System.out.println("Playing song"); } @Override public int rating() { return 5; } } public class Main { public static void main(String[] args) { Playable p = new Song(); p.play(); } } Both methods must be public, and the Playable variable can call play() but not rating().
Exercise
A variable is declared as Drawable d = new Square(2.0);. Why does d.resize(2.0) fail to compile, and how can you call resize safely?
Show answer
The compiler only allows methods declared in the reference type, and Drawable has no resize method. Check with if (d instanceof Resizable), cast with Resizable r = (Resizable) d;, then call r.resize(2.0).
Exercise
Interface A declares int count() and interface B declares long count(). Can one class implement both? Explain.
Show answer
No. The class would need two count() methods with the same parameters that differ only by return type, which Java does not allow. One method cannot return both int and long, so the class fails to compile.