Junior — Middle
What are the differences between an abstract class and an interface in object-oriented programming?
sobes.tech AI
Answer from AI
Abstract class and interface are two ways to define contracts and behaviors in object-oriented programming, but with different features:
- Abstract class can contain both abstract methods (without implementation) and concrete methods, as well as fields (state). It serves as a base class for inheritance.
- Interface defines only method signatures (contract), contains no state, and traditionally no implementation (though default methods are allowed in some languages).
Differences:
- A class can inherit only one abstract class but implement multiple interfaces.
- Abstract class can have constructors, interface cannot.
- Abstract class is used when partial implementation is needed; interface when only the contract.
Example in Dart (Flutter):
abstract class Animal {
void speak(); // abstract method
void sleep() {
print('Sleeping'); // concrete method
}
}
// Interface in Dart is a class with only abstract methods
abstract class Flyable {
void fly();
}
class Bird extends Animal implements Flyable {
@override
void speak() {
print('Bird is speaking');
}
@override
void fly() {
print('Bird is flying');
}
}