Junior — Middle
What are the differences between an abstract class and an interface in object-oriented programming?
sobes.tech AI
Answer from AI
An abstract class and an interface are different mechanisms for describing contracts and behavior in OOP, but with key differences:
-
Abstract class can contain both abstract (without implementation) and concrete methods with implementation. It can have state (fields). Classes inherit from an abstract class and can override methods.
-
Interface describes only a set of methods without implementation and does not contain state. A class implementing an interface must implement all its methods.
Examples of differences:
- An abstract class is suitable when you need to define a base implementation and common state for subclasses.
- An interface is used to describe capabilities that can be implemented by different classes not related by inheritance.
For example, an interface Flyable might describe a method fly(), while an abstract class Bird might contain a field wingSpan and a method sing() with an implementation.