What is the difference in behavior and usage between abstract classes and interfaces in object-oriented programming?
sobes.tech AI
Answer from AI
Abstract classes and interfaces are two different mechanisms for defining contracts and behavior in object-oriented programming, but they have key differences:
-
Abstract class can contain both method implementations and abstract methods without implementations. It serves as a base class that can be inherited. An abstract class can have state (fields), constructors, and access modifiers.
-
Interface only describes a set of methods (contract) that a class must implement. Interfaces do not contain implementations (except default methods in some languages) and do not have state.
Differences in usage:
- A class can inherit from only one abstract class (single inheritance limitation), but can implement multiple interfaces.
- An abstract class is used when you need to provide a base implementation and common state for subclasses.
- An interface is used to define behavior that can be implemented by different classes not related by inheritance.
Example in C#:
abstract class Animal {
public abstract void MakeSound();
public void Sleep() {
Console.WriteLine("Sleeping");
}
}
interface IFlyable {
void Fly();
}
class Bird : Animal, IFlyable {
public override void MakeSound() {
Console.WriteLine("Chirp");
}
public void Fly() {
Console.WriteLine("Flying");
}
}
Here, Animal is an abstract class with partial implementation, and IFlyable is an interface that can be implemented by any class regardless of hierarchy.