A class can have an inheritance relation with a super class. The sub class inherits all the attributes and methods from the super class.

If an object is created using a sub class, it has the methods and attributes of both the sub class and the super class. You can have multiple sub classes that inherit from the same super class.

Inheritance in C#

Inheritance example

The csharp program below creates an object with the defined sub class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System;

namespace InheritanceApplication {
class Bird {
public void quack() {
// quack
Console.WriteLine("Quack");
}
}

// Sub class
class Parrot: Bird {
public void talk() {
// hello
Console.WriteLine("Hello");
}
}
class Example {
static void Main(string[] args) {
Parrot obj = new Parrot();
obj.talk();
obj.quack();

Console.ReadKey();
}
}
}

The above program defines a super class: Bird. Then a sub class is defined (parrot). The sub class inherits all attributes and methods from the super class.

Finally we create an object. The object has both the methods and attributes of the super class and the sub class.

Exercises

  1. Can a class inherit from 2 super classes?
  2. Can super classes inherit from other super classes?
  3. Add another class that inherits from the super class bird.