Sobes.tech
Junior — Middle

What is the difference between using class inheritance and implementing interfaces in object-oriented programming?

sobes.tech AI

Answer from AI

Inheritance of classes and implementation of interfaces are two different mechanisms in object-oriented programming:

  • Class inheritance allows creating a new class based on an existing one, inheriting its fields and methods. It enables code reuse and type hierarchy. In C#, a class can inherit from only one base class (single inheritance).

  • Interface implementation is a way to guarantee that a class implements a set of methods and properties defined in an interface. Interfaces contain only signatures, no implementation. A class can implement multiple interfaces, providing flexibility and enabling more abstract contracts.

Example:

interface IFlyable {
    void Fly();
}

class Bird : Animal, IFlyable {
    public void Fly() {
        Console.WriteLine("Bird is flying");
    }
}

Here, Bird inherits from Animal and implements IFlyable.

What is the difference between using class… - sobes.tech