What are multiple interfaces?
Java allows a class to implement multiple interfaces, which is a way to inherit behavior from multiple sources. An interface in Java is a contract that defines a set of methods without providing the implementation. When a class implements multiple interfaces, it inherits the methods from all those interfaces and must provide implementations for them.
Why do we need multiple interfaces?
Flexibility: A class can adopt features from multiple interfaces, making it highly flexible.
Avoids ambiguity: Since interfaces only provide method signatures, the class can implement the methods explicitly, avoiding any ambiguity.
Clean design: Instead of using multiple classes to inherit features, we can split different behaviors into multiple interfaces and have one class implement them all.
Example
Imagine a media player that supports multiple functions. It can play audio files, record audio, and stream videos. Instead of creating a huge class that does all of these things, we can split these behaviors into different interfaces.
Playable interface: Contains a method to play media.
Recordable interface: Contains a method to record media.
Streamable interface: Contains a method to stream media.
Now, the MediaPlayer
class can implement all three interfaces, providing implementations for each behavior.
Example code