Sub topic 12
Polymorphism Through Interfaces
In the last chapter, an abstract class gave its subclasses a shared method to inherit and a method they had to fill in. That works well when the classes are closely related, like kinds of employees. Sometimes, though, the classes that need to work together have no family link at all. A square and a circle, or a duck and a plane, can share an ability without sharing a parent class. Java handles this with interfaces.
What an Interface Is
An interface is a named list of methods that a class promises to provide. It describes what an object can do. It does not say how the object does it.
A class signs up for that promise with the implements keyword. Once it does, the compiler checks that the class really provides every required method. If one is missing, the code will not compile.
Here are the terms you will see in this chapter:
| Term | Meaning |
|---|---|
| interface | A type that lists methods a class must provide |
| `implements` | The keyword a class uses to adopt an interface |
| abstract method | A method with no body. Every implementing class must write one |
| default method | An interface method that has a body. Classes may keep it or override it |
| interface type | Using the interface's name as the declared type of a variable |
A Worked Example: Shapes
Here is a complete program. The Shape interface asks for an area() method and gives a ready-made describe() method.
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, step by step:
area()inShapehas no body, so it is abstract. Both classes must write their ownarea().describe()has a body and the worddefault, so it is a default method.Squarekeeps the defaultdescribe(). That method callsarea(), and Java runsSquare's version, which gives4.0.Circleoverridesdescribe()with its own text, so the default is never used for circles.
The variable s has the declared type Shape. Each object's runtime type is Square or Circle. Java picks the method from the runtime type. This is the same dynamic dispatch you saw with classes, and it works the same way through an interface type.
Why Implementations Must Be public
Every method in an interface is public, even when you do not type the word. When you override a method, you cannot make it less visible than it was. Because of that, the class's version must also be public.
If you leave off public in Square, you get an error like this:
area() in Square cannot implement area() in Shape
attempting to assign weaker access privileges; was publicOne Class, Many Interfaces
A class can extend only one parent class. It can implement as many interfaces as you like. You list them with commas.
interface Swimmer {
String swim();
}
interface Flyer {
String fly();
}
class Duck implements Swimmer, Flyer {
@Override
public String swim() {
return "Duck paddles";
}
@Override
public String fly() {
return "Duck flaps";
}
}
public class Main {
public static void main(String[] args) {
Duck duck = new Duck();
Swimmer s = duck;
Flyer f = duck;
System.out.println(s.swim());
System.out.println(f.fly());
}
}The output is:
Duck paddles
Duck flapsThere is only one Duck object here, and s and f both point to it. The declared type limits which methods you can call. Writing s.fly() would not compile, because the Swimmer type has no fly() method. The object can fly, but the compiler only sees what the declared type promises.
When Two Default Methods Clash
Suppose two interfaces each give a default method with the same name. A class that implements both would inherit two different bodies. Java will not guess which one you want. It reports a compile error and makes you override the method.
Inside your override, you can still call either default with the form InterfaceName.super.method().
interface Greeter {
default String greet() {
return "Hello";
}
}
interface Welcomer {
default String greet() {
return "Welcome";
}
}
class Host implements Greeter, Welcomer {
@Override
public String greet() {
return Greeter.super.greet() + " and " + Welcomer.super.greet();
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Host().greet());
}
}This prints Hello and Welcome. If you delete the greet() method from Host, the compiler says Host inherits unrelated defaults for greet().
A related rule: if a class inherits a method from its parent class and also a default with the same signature from an interface, the class's method wins. A real method from a class always beats a default.
Interfaces Compared with Abstract Classes
Both tools let you write code against a general type and let Java pick the specific method at runtime. They differ in what they can hold.
| Feature | Abstract class | Interface |
|---|---|---|
| How many a class can use | One (`extends`) | Many (`implements`) |
| Instance fields | Yes | No (only constants) |
| Constructors | Yes | No |
| Methods with bodies | Yes | Yes, as `default` or `static` methods |
| Default visibility of methods | Package-private | Public |
| Best for | Closely related classes sharing state | Unrelated classes sharing an ability |
A simple rule of thumb: if the classes share data and code, think about an abstract class. If they only share what they can do, use an interface. A class can also do both, such as class Hourly extends Employee implements Comparable<Hourly>.
Things to Watch For
- You cannot create an interface object.
new Shape()does not compile. You create aSquareorCircleand store it in aShapevariable. - Missing methods stop the build. A non-abstract class that skips an abstract interface method will not compile.
- Defaults do not hold state. A default method can call other methods of the interface, as
describe()callsarea(). It cannot read fields of the class, because the interface does not know they exist. - Static interface methods are not inherited. A static method in an interface is called as
Shape.someMethod(), never through an object or an implementing class.
Exercise
In the Shape program, suppose you add a class Triangle that implements Shape, writes a public area() method returning 6.0, and does not write describe(). What does System.out.println(new Triangle().describe()) print, and why?
Show answer
It prints "Shape with area 6.0". Triangle does not override describe(), so it uses the default method from Shape. That default calls area(), and dynamic dispatch runs Triangle's area(), which returns 6.0.
Exercise
Given Swimmer s = new Duck(); from the chapter, does s.fly() compile? If not, what is one way to call fly() on the same object?
Show answer
It does not compile, because the declared type Swimmer has no fly() method. You can store the object in a Flyer or Duck variable instead, for example Flyer f = new Duck(); f.fly();. You could also cast s after checking its type, which the next chapter covers.
Exercise
A class Robot implements two interfaces, Walker and Talker, and both have a default method named start(). Robot does not define start(). What happens, and how do you fix it while still using Walker's version?
Show answer
The code does not compile, because Robot inherits two unrelated default start() methods. Fix it by overriding start() in Robot as a public method and calling Walker.super.start() inside it.