A list of abilities
An interface is a list of methods a class promises to have. It says what can be done, not how. A class implements an interface and writes the methods:
interface Playable {
void play();
}
class Guitar implements Playable {
public void play() {
System.out.println("Strum strum");
}
}
class Piano implements Playable {
public void play() {
System.out.println("Plink plonk");
}
}
public class Main {
public static void main(String[] args) {
Playable[] band = {new Guitar(), new Piano()};
for (Playable p : band) {
p.play();
}
}
}Output
Strum strum Plink plonk
Think of it like this: A power socket is an interface. A phone charger, a lamp and a TV are very different, but they all have a plug that fits. The socket doesn't care what's on the other end.
Interface methods are automatically public, so the class must write them as public too.
Many interfaces at once
A class can extend only one class, but it can implement many interfaces:
interface Swimmer {
void swim();
}
interface Flyer {
void fly();
}
class Duck implements Swimmer, Flyer {
public void swim() { System.out.println("Duck paddles"); }
public void fly() { System.out.println("Duck flaps"); }
}
public class Main {
public static void main(String[] args) {
Duck d = new Duck();
d.swim();
d.fly();
}
}Output
Duck paddles Duck flaps
Default methods
Since Java 8 an interface can include a ready-made method marked default. Classes get it for free, but can override it:
interface Greeter {
String name();
default void greet() {
System.out.println("Hello from " + name());
}
}
class Robot implements Greeter {
public String name() { return "Robo"; }
}
public class Main {
public static void main(String[] args) {
new Robot().greet();
}
}Output
Hello from Robo
Abstract class or interface?
| Abstract class | Interface | |
|---|---|---|
| How many can a class use? | one (extends) | many (implements) |
| Can it have fields? | yes | only constants |
| Constructor? | yes | no |
| Use it for... | closely related classes sharing code | an ability many unrelated classes share |