• Home
  • Single, Multi level and Hierarchical Inheritance

Single, Multi level and Hierarchical Inheritance

Agenda

Inheritance in C#

Types of Inheritance in C#:

1) Single Inheritance:

A single derived class inherits from a single base class
public class ClassB : ClassA {
}

2) Multi level Inheritance:

A derived class inherits from a base and then the same derived class acts as a base class for another class.
public class ClassB : ClassA {

}

public class ClassC : ClassB {

}

Types of Inheritance in C#

3) Hierarchical Inheritance:

One class serves as a superclass (base class) for more than one subclass.

Multiple Inheritance ( Through Interfaces Only)

One class can have more than one superclass and inherit features from all parent classes. As C# does not support multiple inheritance with classes, user can achieve multiple inheritance only through Interfaces in C#.

C# Single and Multi-level Inheritance

 public class ClassA
{ public int a = 20;

public void add(int x, int y)

{

Console.WriteLine(x + y);

} }

public class ClassB : ClassA

{ public int b = 30;

public void substraction(int x, int y)

{

Console.WriteLine(x - y);

} }

public class ClassC : ClassB

{ public int c = 30;

public void multiplication(int x, int y)

{

Console.WriteLine(x * y);

} }

static void Main() {

ClassA objA = new ClassA();

Console.WriteLine(objA.a); objA.add(10, 20);

ClassB objB = new ClassB();
Console.WriteLine(objB.a); objB.add(30, 20);

Console.WriteLine(objB.b); objB.substraction(30, 20);

ClassC objC = new ClassC();

Console.WriteLine(objC.a); objC.add(30, 20);

Console.WriteLine(objC.b); objC.substraction(30, 20);

Console.WriteLine(objC.c); objC.multiplication(30, 20);

}

Object Oriented Programming Structure
Inheritance
Polymorphism
Encaptulation
Abstraction

public class ClassA
{
public int a = 20;
public void add(int x, int y)
{
Console.WriteLine(x + y);
}
}

public class ClassD : ClassA
{
public int d = 50;
public void division(int x, int y)
{
Console.WriteLine(x/y);
}
}

public class ClassB : ClassA
{
public int b = 30;
public void substraction(int x, int y)
{
Console.WriteLine(x - y);
}
}

public class ClassC : ClassB
{
public int c = 30;
public void multiplication(int x, int y)
{
Console.WriteLine(x * y);
}
}

ClassA objA = new ClassA();
Console.WriteLine(objA.a);
objA.add(10, 20);

ClassB objB = new ClassB();
Console.WriteLine(objB.a);
objB.add(30, 20);
Console.WriteLine(objB.b);
objB.substraction(30, 20);

// Console.WriteLine(objB.a); error while accessing Class a variable without Inheritance
ClassC objC = new ClassC();
Console.WriteLine(objC.a);
objC.add(30, 20);
Console.WriteLine(objC.b);
objC.substraction(30, 20);
Console.WriteLine(objC.c);
objC.multiplication(30, 20);

ClassD objD = new ClassD();
Console.WriteLine(objD.a);
objD.add(30, 20);
Console.WriteLine(objD.d);
objD.division(30, 10);