Inheritance in C#

Pin

In one of my previous articles, I introduced you to object-oriented programming (OOP). There are three pillars of OOP which are cumulatively known as PIE: Polymorphism, Inheritance, and Encapsulation. In this article, we will focus on Inheritance and the different ways of implementing inheritance in C#.

Inheritance

Before diving into C# inheritance, let’s first discuss what inheritance is in the real world because the two concepts are pretty similar. Google defines inheritance as “a thing that is inherited”. Let’s discuss the example of inheritance between parents and children. Children can inherit many physical features from their parent’s such as blood group, eye color, height, complexion, etc. They also develop some features of their own that were not present in their parents. Similarly, children may inherit parent’s property and build some property of their own. So in short, inheritance can be defined as the phenomena where a child inherits some of the characteristics of the parents and develops some characteristics specifically to the child.

Now let’s take this concept to C# inheritance. In C#, a child class can inherit from a parent class. In such scenarios, all the characteristics i.e. methods, variables, properties (other than those specified as private) are inherited by the child class. The child class can readily use these characteristics without defining them again. However, there is no point in inheriting from parent class if a child class doesn’t contain properties or methods that are specific to the child. The reason is if you only need parent’s characteristics, you can use parent class and object and there is no need to defined the child class.

Inheritance basically implements “is a” relation. For instance, a Teacher is a person; a Student is a person; etc.

Base or Parent Class

The class from which other classes inherit is called base class or parent class. All the common characteristics should be encapsulated inside the parent class.

Derived or Child Class

The class which inherits from another class is called derived or child class. All the specific characteristics should be encapsulated inside child class.

Take a look at the following example to see how inheritance is actually implemented in C#.

class Person // Parent class
{
    public string Name;
    public int Age;
    public void GetNameAndAge();
    {
	Console.WriteLine("The person has name: " + Name + " and age: " + Age);
    }
}

class Teacher : Person // Child class
{
    public string Subject;
}

class Student : Person // Child class
{
    public int StudentId;
}

In the above code, a class Person is initialized. This is a parent class of Teacher and Student class since a Teacher is a Person and Student is also a Person. We discussed earlier that all the common characteristics should be encapsulated in the Parent class.

So what is common between a Teacher and a Student? Teacher and Student both have a name and both must have an age. So for now, let’s add these two variables in the parent class Person. Parent class Person also has a method that basically prints name and age on screen, called “GetNameAndAge”.

Next, we create a child class Teacher and inherit it from the parent class Person. To inherit from a class you need to add colon “:” after the child class followed by the name of the parent class. Teacher class by default has Name and Age variables along with the “GetNameAndAge” method available to it. Think of some attributes that are not common in Teacher and Student class but are specific to Teacher class. Subject is one of those attributes. A teacher has a Subject but a student doesn’t. Therefore, Subject cannot be encapsulated in parent class Person. It has to be added inside the child class Teacher.

Similarly, we created a Student class, inherited it from Parent person class and then added a “StudentId” attribute to Student class which is specific to students. Now, we can create objects of Person, Teacher and Student class and see how the child class objects use parent class variables and methods.

Person person = new Person();
person.Name = "Mike";
person.Age = 20;

Teacher teacher = new Teacher();
teacher.Name = "Thomas";
teacher.Age = 35;
teacher.Subject = "Math";
teacher.GetNameAndAge();

Student student = new Student();
student.Name = "Sara";
student.Age = 19;
student.StudentId = 10506;
student.GetNameAndAge();

In the above code, we created objects of Person, Teacher and Student class. It can be seen that Teacher and Student class objects don’t have name and age variable, but since they have inherited the variables from Person class, they are accessing these variables.

Calling Parent Class constructor via Child Class

You may be wondering how we can initialize base class variables by calling the constructor of the child class. Take a look at the following example.

class Person // Parent class
{
    public string Name;
    public int Age;
    public Person(string name, int age)
    {
	Name = name;
	Age = age;
    }
}

class Teacher : Person // Child class
{
    public string Subject;

    public Teacher(string name, int age, string subject) : base(name, age)
        {
            Subject = subject;
        }
}

class Student : Person // Child class
{
    public int StudentId;

    public Student(string name, int age, int studentId) : base(name, age)
    {
        StudentId = studentId;
    }
}

In the above code, we have added a constructor to the Person class. This constructor initializes the name and age variables. Now, take a look at the child class Teacher. Here we have declared a constructor with three parameters. At the end of the constructor we have used colon “:” followed by keyword “base” and two parameters name and age. Here the keyword “base” calls the base class constructor and passes it the name and age variables. Notice that these name and age variables are the first two parameters in the Teacher class. Teacher class constructor also has a third parameter which initializes the Teacher class variable “Subject”.

So when you call the Teacher class constructor with three parameters: name, age, and subject, the base class constructor is called and first two parameters are passed to it. The third parameter initializes the child class variable. Student class constructor is initialized in the same way. Take a look at the following code to see how constructors of Person, Teacher, and Student classes are called.

Person person = new Person("Mike", 20);
Teacher teacher = new Teacher("Thomas", 35, "Math");
Student student = new Student("Sara", 19, 10506);

Abstract Class

An abstract class is a class that cannot be instantiated or in other words a class whose object cannot be created. Abstract classes are implemented via their derived classes. But why would we need a class with no object? The answer is simple. Some classes are nothing on their own. For instance, in the context of a School database a Person class is nothing. We do not have any “Person” entity in a school. However, we have Teachers and Students. Therefore, we can make Person an abstract class and provide its implementation via Teachers and Students. To create an abstract class we use the “abstract” keyword. Take a look at the following example:

abstract class Person // Parent class
{
    public string Name;
    public int Age;
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

class Teacher : Person // Child class
{
    public string Subject;

    public Teacher(string name, int age, string subject) : base(name, age)
    {
        Subject = subject;
    }
}

Now if you try to create an object of the Person class, the compiler won’t let you do so. Take a look at the following code snippet.

Person person = new Person("Mike", 20); // This will not compile

Teacher teacher = new Teacher("Thomas", 35, "Math"); // This will work fine

In the above example, you will see that we can create objects directly from the Teacher class but not the Person class.

In this article, we discussed inheritance. We saw how to inherit from a parent class and how to set a parent as abstract. In my next article, we are going to discuss polymorphism.