C# Tutorial : Lesson 12 – Inheritance – Part I

Partho Sarathi

25 Apr, 2009 · 6 minutes read

  • Share:

One of the important aspects of the Object Oriented Methodologyis relationship. Objectsdo not exist as isolated entities, rather, they exhibit some kind of relationship with other objects. Some of the common relationships between the classes are listed below:-

Instantiation Relationship

This is the relationship that exists between a classand its instance or object. Real world examples of such a relationship can be:-

  • A Ferari is a Car
  • A Mobile Phone is a type of electronic device
class Car
{
	string Model;
	string Company;
	string SerialNumber;
}

void Main(string[] args)
{
	Car MyCar = new Car();	// Instantiation Relationship between MyCar & Car
}
Composition Relationship

Classes can be nested i.e a Class can contain another class. The relationship between two such classes is called composition relationship.

Composition

The following code represents the Composition relationship that is depicted in the above diagram.

class Car
{
    string SerialNumber;
    string Model;
    string Color;

    class Engine
    {
        string Type;
        string Model;
    }

    class Wheel
    {
        int Width;
        string Manufacturer;
    }
}
Utilization Relationship

The concept of OOP allows a class to make use of another class i.e delegate some portion of its work to another specialized class. The relationship between these two classes is termed as utilization. Ferari an object of the car class, is driven by Michael, an object of the driver class. These two entities have a utilization relationship between them.

The following code snippet demonstrates the utilization relationship between the Sorterand the Swapperclass.

class Sorter
{
    public static void Sort(int[] A)
    {
        for (int I = 0; I < A.Length - 1; I++)
        {
            for (int J = I + 1; J < A.Length; J++)
            {
                if (A[I] > A[J])
                {
                    // Utilizes the Swapper Class to do the swapping
                    Swapper.Swap(A[I], A[J]);
                }
            }
        }
    }
}

class Swapper
{
    public static void Swap(ref int Num1, ref int Num2)
    {
        int Temp = Num1;
        Num1 = Num2;
        Num2 = Temp;
    }
}

This example uses the bubble sort algorithm to sort an array of integers in the ascending order. While sorting, two elements of the list need to be swapped when they are not arranged ascendingly. The Sorter class employs the Swapper class for this job thus utilizing it.

Inheritance

Just as a child inherits qualities from his/her parents, a class can inherit data members and functions from another class. Consider the following class diagram:-

The Mammals class is the base class as it inherits its attributes to other classes. Dogs, cats & Humans are its child classes. This hierarchy is derived from the common set of attributes that the classes share. Mammals, for example are warm blooded, vertebrates, possess external ears and have hair on their body. These characteristics also pertain to Dogs, Cats, Humans, Lions, Tigers and Leopards, thus making them mammals. In C#, a class can have multiple child classes but only 1 base class. Multiple inheritance which existed in languages such as C++ has been scrapped because they tend to cause more problems than they solve.

Some key terms related to Inheritance are listed below.

  • Base(Super) Class– The class that inherits its properties to other classes.
  • Child(Sub) Class– The class that inherits its properties from other classes.
  • Multi-level Inheritance– A class which inherits from another class, serves as the base class for a third class. In the preeceding diagram, Lions, Tigers & Leopards are derived from the Cats class which itself is derived from the Mammals class. This is called multi-level inheritance.
  • Generalization– Classes that inherit from the same base class have certain common attributes which have been inherited from the common base class. This relationship is called Generalization.
  • Specialization– It refers to the uncommon characteristics of a sub class, those that make it different from others. When we say that Human is a kind of Mammal, we imply that they have the common properties of Mammals along with some specialized characteristics that make them different from other Mammals – They walk on two legs. Specialization is the opposite of Generalization.
Implementing Inheritance

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Cars MyFerari = new Cars();
            MyFerari.NumberOfWheels = 4;
            MyFerari.Drive();
        }
    }

    public class Vehicles
    {
        private string Name;
        public int NumberOfWheels;
        public void Drive()
        {
        }
    }

    public class Cars : Vehicles
    {

    }
}

In this example, the Cars class is a sub class which is derived from the Vehicles class. The Cars class inherits the data member NumberOfWheels and the member function – Drive() from the Vehicles class. So, the MyFerari object of the Car class has access to these members.

Note: Private members are not accessible from the sub class. So, the follwoing code would cause a ‘ConsoleApplication1.Vehicles.Name’ is inaccessible due to its protection level.error.

MyFerari.Name = "Ferari";
Determining Inheritance Hierarchies

This process is very simple as the only thing one needs to remember is that the sub class should be a type of the base class. For example: Human is a type of Mammal, Car is a type of vehicle and so on.

Note: Improper usage of Inheritance will not result in any syntactical error. But, the design model for the program would be at fault.

Constructor Inovking Order

Constructorsbeing unique to a class are not inherited. Whenever an object of a child class is created, the constructor of both the parent and the child class is invoked. The parent class must come into existence before its child class can. Therefore, the constructor of the base class is invoked first followed by the constructor of the derived class. The destructors are invoked in the opposite order – derived to base. This is because the child class must be destroyed before the parent class.

The following program confirms these two order.

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Cars MyFerari = new Cars();
            Console.ReadLine();
        }
    }

    public class Vehicles
    {
        public Vehicles()
        {
            Console.WriteLine("Vehicles -> Constructor Invoked");
        }

        ~Vehicles()
        {
            Console.WriteLine("Vehicles -> Destructor Invoked");
        }
    }

    public class Cars : Vehicles
    {
        public Cars()
        {
            Console.WriteLine("Cars -> Constructor Invoked");
        }

        ~Cars()
        {
            Console.WriteLine("Cars -> Destructor Invoked");
        }
    }
}
  • Share:

The cleanest blogging platform


2024 © Maxotek. All rights reserved.