Abstract vs Interface Comparison
This program compares abstract class and interface usage.
Problem Statement
Write a Java program to demonstrate difference between abstract class and interface.
Source Code
| 1 | abstract class Animal { |
| 2 | abstract void sound(); |
| 3 | void sleep(){ System.out.println("Animal sleeps"); } |
| 4 | } |
| 5 | interface Pet { |
| 6 | void play(); |
| 7 | } |
| 8 | class Dog extends Animal implements Pet { |
| 9 | void sound(){ System.out.println("Dog barks"); } |
| 10 | public void play(){ System.out.println("Dog plays fetch"); } |
| 11 | } |
| 12 | public class AbstractVsInterface { |
| 13 | public static void main(String[] args) { |
| 14 | System.out.println("Eduinq Abstract vs Interface"); |
| 15 | Dog d=new Dog(); |
| 16 | d.sound(); d.sleep(); d.play(); |
| 17 | } |
| 18 | } |
Program Output
Eduinq Abstract vs Interface Dog barks Animal sleeps Dog plays fetch
Explanation
Abstract class can have both abstract and concrete methods. - Interface only defines abstract methods (Java 8+ allows default/static). - Dog inherits from abstract class and implements interface, showing how both can coexist. - This demonstrates design flexibility: abstract classes for partial implementation, interfaces for contracts. Conclusion: Shows difference between abstract class and interface.