Interface Polymorphism Example
This program demonstrates polymorphism using interfaces.
Problem Statement
Write a Java program where Playable interface is implemented by Guitar and Piano.
Source Code
| 1 | interface Playable { void play(); } |
| 2 | class Guitar implements Playable { public void play(){ System.out.println("Eduinq Playing Guitar"); } } |
| 3 | class Piano implements Playable { public void play(){ System.out.println("Eduinq Playing Piano"); } } |
| 4 | public class InterfacePolymorphism { |
| 5 | public static void main(String[] args) { |
| 6 | System.out.println("Eduinq Interface Polymorphism"); |
| 7 | Playable p1=new Guitar(); |
| 8 | Playable p2=new Piano(); |
| 9 | p1.play(); p2.play(); |
| 10 | } |
| 11 | } |
Program Output
Eduinq Interface Polymorphism Eduinq Playing Guitar Eduinq Playing Piano
Explanation
Interfaces define contracts that multiple classes can implement. - Guitar and Piano implement Playable, each with its own behavior. - Polymorphism allows interface references to point to different implementations, enabling runtime flexibility. - This is widely used in enterprise systems where interchangeable components must adhere to a standard contract but provide unique implementations, such as payment gateways or notification services. Conclusion: Shows interface polymorphism example.