Junior — Middle
What is the main difference between an abstract class and an interface in object-oriented programming?
sobes.tech AI
Answer from AI
The main difference between an abstract class and an interface is that an abstract class can contain method implementations and state (fields), whereas an interface only defines method signatures without implementation (up to C# 8.0). An abstract class is used when you need to provide a base implementation and common functionality for subclasses, while an interface is used to define a contract that classes must implement, regardless of their hierarchy.
Example:
// Abstract class
public abstract class Animal {
public void Eat() {
Console.WriteLine("Eating");
}
public abstract void MakeSound();
}
// Interface
public interface IMovable {
void Move();
}
// Class inheriting from abstract class and implementing interface
public class Dog : Animal, IMovable {
public override void MakeSound() {
Console.WriteLine("Bark");
}
public void Move() {
Console.WriteLine("Run");
}
}