Junior — Middle
What is the difference between using an abstract class and an interface when defining contracts for classes?
sobes.tech AI
Answer from AI
An abstract class and an interface in C# serve to define contracts but have key differences:
- Abstract class can contain method implementations, fields, constructors, and properties. It is used when you need to establish a base implementation and common functionality for subclasses.
- Interface only defines method signatures, properties, and events without implementation (up to C# 8.0; starting from C# 8.0, interfaces can contain default implementations).
Also, a class can inherit from only one abstract class but can implement multiple interfaces.
Example:
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"); }
}
Thus, an abstract class is suitable for common base behavior, while an interface is for defining a set of capabilities that can be implemented by different classes.