Sub topic 12
Polymorphism Through Interfaces
In the last chapter, an abstract class gave its subclasses shared code and a list of methods they had to provide. But a Java class can extend only one class. What can you do when unrelated classes need to be used the same way? You can use an interface.
What an Interface Is
An interface is a type that lists methods a class promises to have. A class makes that promise with the implements keyword. Once a class implements an interface, you can refer to its objects through the interface type. Polymorphism then works the same way it does with a superclass.
An interface can also contain a default method. A default method is a method with a body, written inside the interface with the default keyword. Classes get it for free, and they can override it if they want different behavior.
A Worked Example
Here, Square and Circle share no parent class except Object. They both implement Shape.
interface Shape {
double area();
default String describe() {
return "Shape with area " + area();
}
}
class Square implements Shape {
private final double side;
Square(double side) {
this.side = side;
}
@Override
public double area() {
return side * side;
}
}
class Circle implements Shape {
private final double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
@Override
public String describe() {
return "Circle of radius " + radius;
}
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = { new Square(2), new Circle(1) };
for (Shape s : shapes) {
System.out.println(s.describe());
}
}
}Save this as Main.java, then run javac Main.java and java Main. The output is:
Shape with area 4.0
Circle of radius 1.0Here is what happens at each step:
- The array is declared as
Shape[], so each element's declared type isShape. Squaredoes not overridedescribe(), so it uses the default version. That version callsarea(), and Java runsSquare'sarea().Circleoverridesdescribe(), so Java runsCircle's version.
The loop never asks which kind of shape it has. Java picks the right method from each object's runtime type.
Abstract Class or Interface?
| Question | Abstract class | Interface |
|---|---|---|
| How many can a class use? | Only one (`extends`) | Many (`implements A, B`) |
| Can it hold instance fields? | Yes | No (only constants) |
| Can it have constructors? | Yes | No |
| Best for | Closely related classes sharing state | Unrelated classes sharing a role |
A simple rule for beginners: if the classes share data and setup code, use an abstract class. If they only need to share a set of abilities, use an interface.
Exercise
In the example above, suppose you remove the public keyword from Circle's area() method, so it reads double area(). What happens when you compile, and why?
Show answer
The compiler reports an error. Interface methods are implicitly public, and an overriding method cannot have weaker access than the method it overrides. Package-private access is weaker than public.
Exercise
Add a class Rectangle that implements Shape with a width and a height, and that does not override describe(). What does new Rectangle(2, 3).describe() return?
Show answer
It returns "Shape with area 6.0". Rectangle uses the default describe() method, and that method calls Rectangle's own area(), which returns 2 * 3 = 6.0.