Does Abstract class support multiple Inheritance? in c# with example

No, in C#, an abstract class does not support multiple inheritance. C# supports single inheritance, which means a class can inherit from only one base class, whether it is abstract or not.

Here's an example to illustrate this:

// Abstract class public abstract class Animal { public abstract void Sound(); } // Base class public class Mammal { public void Walk() { Console.WriteLine("Walking..."); } } // Derived class inheriting from an abstract class and a base class public class Dog : Animal // Error: C# does not support multiple inheritance { public override void Sound() { Console.WriteLine("Woof!"); } } // Main class public class Program { public static void Main(string[] args) { Dog dog = new Dog(); dog.Walk(); // Error: Dog does not inherit from Mammal dog.Sound(); } }

In this example, the Animal class is declared as an abstract class with an abstract method Sound(). The Mammal class is a base class that defines a non-abstract method Walk(). The Dog class attempts to inherit from both Animal and Mammal, but it will result in a compilation error because C# does not support multiple inheritance.

To work around this limitation, you can use interfaces or utilize composition to achieve similar behavior by including objects of other classes within your class.


 

Post a Comment

Previous Post Next Post