Interface vs Abstract Class
Interface
- 100% abstraction (prior to Java 8).
- Can have default/static methods (Java 8+).
- No constructors.
- Multiple inheritance allowed.
Abstract Class
- Partial abstraction.
- Can have constructors and fields.
- Single inheritance only.
Examples
Interface
interface Animal {void makeSound(); // Method declaration}class Dog implements Animal {public void makeSound() {System.out.println("Bark");}}interface Animal { void makeSound(); // Method declaration } class Dog implements Animal { public void makeSound() { System.out.println("Bark"); } }interface Animal { void makeSound(); // Method declaration } class Dog implements Animal { public void makeSound() { System.out.println("Bark"); } }
Enter fullscreen mode Exit fullscreen mode
Abstract Class
abstract class Vehicle {abstract void start(); // Abstract methodvoid stop() {System.out.println("Vehicle stopped"); // Concrete method}}class Car extends Vehicle {void start() {System.out.println("Car started");}}abstract class Vehicle { abstract void start(); // Abstract method void stop() { System.out.println("Vehicle stopped"); // Concrete method } } class Car extends Vehicle { void start() { System.out.println("Car started"); } }abstract class Vehicle { abstract void start(); // Abstract method void stop() { System.out.println("Vehicle stopped"); // Concrete method } } class Car extends Vehicle { void start() { System.out.println("Car started"); } }
Enter fullscreen mode Exit fullscreen mode
When to Use What?
Use Interface When:
- You need to define a contract for unrelated classes.
- Multiple inheritance of type is required.
- You want to provide default or static methods without affecting the implementing classes.
Use Abstract Class When:
- Classes share a common base and need to share code.
- You want to provide some implemented methods and enforce others to be overridden.
- You need constructors or non-constant fields.
Conclusion
Both interfaces and abstract classes are powerful tools in Java, and choosing between them depends on your application’s needs. Use interfaces to define behaviors across unrelated classes and abstract classes for shared code in a class hierarchy.
By understanding their differences and strengths, you can write cleaner and more maintainable code. Happy coding!
原文链接:What are the key differences between an Interface and an Abstract class?
© 版权声明
THE END
暂无评论内容