Java
Multiple interfaces
Learn to implement multiple interfaces.
Implementing multiple interfaces
A class can implement more than one interface. Interface names are separated by commas. The class must write all methods of all interfaces.
Example: class Document implements Printable, Savable { ... }. Here Document implements both the Printable and Savable contracts. It must write the methods of both interfaces. Java lets classes inherit from a single class; but they can implement multiple interfaces. This meets the need for multiple inheritance safely. As long as there is no conflict, a class can implement as many interfaces as it wants. It is key to flexible design.
The advantage of multiple interfaces
Implementing multiple interfaces lets a class take on different roles. The same object can be used as different contracts in different contexts. This increases code reuse.
Example: if Document is both Printable and Savable, it can be passed to a printAll(Printable[] items) method and also to a saveAll(Savable[] items) method. One class plays a role in two different workflows. This keeps the class hierarchy flexible. Each role is represented by an interface; the class combines roles. This approach helps large systems stay clean. New roles can be added as needed.
Exercise Implement two interfaces on the Document class
Define an interface Printable; add the void print() signature. Define a second interface Savable; add the void save() signature. Then write class Document implements Printable, Savable; write both methods as public void with bodies. The print body runs System.out.println("Printing");, the save body runs System.out.println("Saving");. In main create Document d = new Document(); then call d.print() and d.save().
Show example solution
interface Printable {
void print();
}
interface Savable {
void save();
}
class Document implements Printable, Savable {
public void print() {
System.out.println("Printing");
}
public void save() {
System.out.println("Saving");
}
}
class Main {
public static void main(String[] args) {
Document d = new Document();
d.print();
d.save();
}
}
Test yourself
-
How are multiple interface names separated?
- With a comma
- With a dot
- With a plus
- With and
Show answer
With a comma — They are separated with a comma.
-
Match the multiple interface roles
- Printable
- Printing role
- Savable
- Saving role
- Document
- Class combining roles
- implements
- Implementation keyword
-
Complete the multiple implements line
class Document implements Printable, ____ {
public void print() { }
public void save() { }
}
Show answer
class Document implements Printable, Savable {
public void print() { }
public void save() { }
}
Next lesson: Summary - Interface