Object-Oriented Programming : Inheritence

KristiadhyKristiadhy
5 min read
  • Inheritance allows the creation of new classes called derived classes (subclass/child class).

  • The class that serves as the parent of the derived class is usually called the base class (parent class/superclass).

  • Derived classes can use methods written in the base class, reducing code duplication.

Real-world example.

The relationship between animals and dogs.

  • Animals are a general category that includes various living creatures with basic traits like breathing and moving.

  • Dogs, as a type of animal, inherit these traits but also have specific characteristics, such as barking and loyalty to their owners.

  • In this illustration, animals are referred to as the base class/parent class/superclass, while dogs are referred to as the derived class/child class/subclass, inheriting basic traits from animals and adding their own unique traits.

Code example.

Here is an example of creating a class for animals (class Animal) and dogs (class Dog).

public class Animal
{
    public void Eat()
    {
        Console.WriteLine("Animal is eating.");
    }
}

public class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Dog is barking.");
    }
}

Here is an example when the dog class (which is a subclass of the Animal class) is initialized into an object.

Dog myDog = new Dog();
myDog.Eat();
myDog.Bark();

In the code above, we can see that the variable myDog is declared with the object type 'Dog'. When calling a method, the myDog object can call the Eat() method, which is a method from its parent class, 'Animal', but can also call the Bark() method, which is a unique method of the 'Dog' class itself.

Rules of Inheritance to consider.

In using inheritance, there are several rules to consider, including:

Rule 1:

A child class can access members of the parent class, but the parent class can never access members purely defined in the child class.

// Code example 1
Dog myDog = new Dog();
myDog.Eat();
myDog.Bark(); // This part does NOT result in an error.

// Code example 2
Animal myAnimal = new Animal();
myAnimal.Eat();
myAnimal.Bark(); // This part results in an error.

The last line in code example 2 above will result in an error because Bark() is a method or function specific to Dog, which is a child class, not a method belonging to Animal as the parent class of Dog.

Rule 2:

We can initialize a parent class variable using a child class instance. With this technique, the parent class will act as a reference variable.

Animal myAnimal= new Dog();
myAnimal.Eat();
myAnimal.Bark();

In the variable declaration above, we initialize the variable myAnimal with its object type as Dog. In the last line of that code, the compiler will recognize it as an error. Why? Because at compile time, the compiler checks the reference variable (left side), while the object type (right side) is checked at runtime (we will explore more about what happens at compile time and runtime in the topic of Polymorphism). Since at compile time the reference variable (left side) is used, which is the Animal class, and that class does not have a Bark() method/function, an error occurs.

Rule 3:

If the parent class has a constructor, that constructor must be accessible by the child class.

public class Animal
{
    Animal() // Constructor from the parent class
    {
        Console.WriteLine("Animal Constructor is Called");
    }
    public void Eat()
    {
        Console.WriteLine("Animal is eating.");
    }
}

public class Dog : Animal
{
    public Dog() // Constructor from the child class
    {
        Console.WriteLine("Dog Constructor is Called");
    }
    public void Bark()
    {
        Console.WriteLine("Dog is barking.");
    }
}

In the section above, an error will occur because the animal constructor does not allow access by other classes outside itself (the default modifier on a class is private). The solution is to provide a modifier that allows the child class to access the constructor of its parent class, for example: By adding the "Public" access modifier to the Animal constructor, no error will occur.

Rule 4:

If the parent class constructor is given parameters, the child class constructor cannot implicitly call its parent constructor without passing parameters.

public class Animal
{
    public Animal(int number)
    {
        Console.WriteLine($"Animal Constructor is Called : {number}");
    }
    public void Eat()
    {
        Console.WriteLine("Animal is eating.");
    }
}

public class Dog : Animal
{
    // When creating a constructor for the child class, you must also 
    // pass parameters to its base class.
    // If not (if the code ": base(10)" is not written), an error will occur.
    public Dog() : base(10)
    {
        Console.WriteLine("Dog Constructor is Called");
    }
    public void Bark()
    {
        Console.WriteLine("Dog is barking.");
    }
}

Notice the code above, when declaring the constructor in the child class, we pass parameters to the base class constructor or its parent class, so the code is correct and not in error. However, if “: base(10)” is not written, meaning no parameters are passed to the parent class, an error will occur.

Types of inheritance.

Single Inheritance.

Where a class, known as a derived class, is based on another class, known as the base class (or parent class).

public class Animal
{
    public void Eat()
    {
        Console.WriteLine("Animal is eating.");
    }
}

public class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Dog is barking.");
    }
}

Multilevel Inheritance.

Where a class is derived from another derived class, creating an inheritance chain.

public class Grandfather
{
    public void Display()
    {
        Console.WriteLine("This is the grandfather class");
    }
}

public class Father : Grandfather
{
    public void Show()
    {
        Console.WriteLine("This is the father class");
    }
}

public class Child : Father
{
    public void DisplayChild()
    {
        Console.WriteLine("This is the child class");
    }
}

Hierarchical Inheritance.

Where multiple classes are derived from a single base class, forming a tree-like structure.

public class Parent
{
    public void Display()
    {
        Console.WriteLine("This is the parent class");
    }
}

public class Child1 : Parent
{
    public void Show1()
    {
        Console.WriteLine("This is the first child class");
    }
}

public class Child2 : Parent
{
    public void Show2()
    {
        Console.WriteLine("This is the second child class");
    }
}

We can see this more clearly in the following image.

We have learned about the concept of Inheritance in OOP, next we will look at the next concept of OOP, which is Encapsulation.

0
Subscribe to my newsletter

Read articles from Kristiadhy directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Kristiadhy
Kristiadhy

Experienced Full Stack .NET developer with a proven track record of designing and implementing robust business applications. Proficient in using ASP.NET Core Web API, Blazor, and WinForms to deliver high-quality, efficient code and scalable solutions. Strong focus on implementing industry best practices for cleaner and scalable outcomes.