In C#, both abstract classes and interfaces are used to define a contract that must be implemented by derived classes. However, there are some differences between the two:
Implementation:
An abstract class can provide a default implementation for some or all of its members, while an interface cannot provide any implementation.
Multiple Inheritance:
A class can only inherit from one abstract class, but it can implement multiple interfaces. This means that interfaces are more flexible when it comes to multiple inheritance.
Access Modifiers:
Members of an interface are always public, while members of an abstract class can have any access modifier.
Constructor:
An interface cannot have a constructor, while an abstract class can have a constructor that is called when a derived class is instantiated.
Fields:
An interface cannot have fields, while an abstract class can have fields.
Here's an example to demonstrate the difference between an abstract class and an interface:
public interface IAnimal
{
string Name { get; set; }
void MakeSound();
}
public abstract class Animal
{
public string Name { get; set; }
public virtual void MakeSound()
{
Console.WriteLine("Animal makes a sound.");
}
public abstract void Eat();
}
public class Dog : Animal, IAnimal
{
public override void MakeSound()
{
Console.WriteLine("Dog barks.");
}
public override void Eat()
{
Console.WriteLine("Dog eats meat.");
}
}
In the above example, IAnimal is an interface that defines a Name property and a MakeSound() method. Animal is an abstract class that defines a Name property, a virtual MakeSound() method, and an abstract Eat() method. The Dog class derives from Animal and implements IAnimal, and provides its own implementation for the MakeSound() and Eat() methods.
In summary, the main differences between an abstract class and an interface are that an abstract class can provide a default implementation for some or all of its members, while an interface cannot provide any implementation. An interface can be implemented by multiple classes, while a class can only inherit from one abstract class.