Inheritance

Here today I will describe the main concept of the inheritance in .net c# language. The inheritance gives us a possibility of creating new class which will be an extension of other class. Let me give an example. We have a class 'Animal' defined below:

    class Animal
    {
        public Animal(string latinName) { LatinName = latinName;}
        public string LatinName         { get; private set; }
        public int NumberOfLegs         { get; set; }
        public int Weight               { get; set; }
        public void Eat()               { }
    }
    

Now you have to have class 'Tiger' which will have the same properties and methods as 'Animal' but will be equipped with a method 'Bite'. You can of cource copy whole class Animal, change the name and add this method. This will be VERY BAD solution. You will have a redundant code. For the system those two classes will be completelly different, so you lost ability to treat them as the same type of object. The best solution is to create new class which will Inherit all things from the Animal class and add one additional method.

    class Tiger : Animal
    {
        public void Bite() {}
    }
    

When we will try to compile it, we will be disappointed. The system throws: Error 1 'Animal' does not contain a constructor that takes 0 arguments. The reason of this problem is that child class has to initialize a members of parent class. The 'Tiger' class has one default constructor without parameters. This constructor tries to call an without-parameters constructor of base class. Unfortunatelly in the base class we added a constructor with one parameter so system didn't generate default without-parameters constructor. To fix it we can just add the without-parameters constructor to 'Animal' Class. After that our code starts to work.

Tiger class

As shown above the new Tiger class inherits all functionality from base class. Almost all, When we will try to initialize the Tiger class by passing to its constructor the latin name then we find a problem. 'Tiger' does not contain a constructor that takes 1 arguments. The reason of this problem is that the constructors aren't inherited by child. We have to add this constructor to Tiger class. During adding the constructor we have to remember about invoke the constructor of parent class. In this example it is obvious because the setter of LatinName property is private and we don't have access to it from Tiger class.

    public Tiger(string latinName):base(latinName)
    {}
    

In above example I have used the 'base' keyword. There are two important keywords in c#.

  • base
  • this

Both of them can be used in constructor as a call to another constructor. In the first case the 'base(x)' calls the constructor of base class with argument x. The second case the this(x) calls the constructor of the same class with argument x. The second way to use those two keyword is to pointing on particular class member. For example:

    base.method1 //will point the method1 of base class.
    this.method2 //will point the method2 of current class.
    

Polymorphism

Let's talk about one of the most useful part of inheritance. The polymorphism is a ability to treat one object as other object. Returning to our example about animals. We know that most of the animals can make sounds. Each animal does different type of sound. So to implement it we have to add additional method to all animal's classes. Let's start with the 'Tiger' class.

    class Tiger : Animal
    {
        public Tiger(string latinName):base(latinName) {}
        public void Bite() {}
        public string MakeSound() { return "Wraaau";}
    }
    

Let's assume the 'MakeSound' function play the relevant sound instead of returning text representation of this sound. Text representation is just better for further clarification and understanding. Everybody knows that not only tiger can make sound. There are a lot of other animals with this ability. For each of them we should implement this function. What happens in the future when we will have big set of various animal, and we will want to on each of them who has makeSound function, invoke this function. Identifying whether an object has relevant function is theoretically possible, but you shouldn't do this. There are two solutions of this problem.

  • Implement the makeSound method in base class and makes it virtual.
  • Create new interface and implement it, in each animal which is able to make sound.

Let's start for the first possibility as the virtual methods are core of polymorphism. At first we have to create the virtual method in the base class, but does Animal is relevant place for it? I don't think so, not everyone animal make sound. We create then additional class SoundableAnimal

    class SoundableAnimal:Animal
    {
        public SoundableAnimal(string latinName): base(latinName)   {}
        public virtual string MakeSound()                           {return "";}
    }
    

Next change the Tiger class to inherit from SoundableAnimal instead of animal.

        class Tiger : SoundableAnimal
        {
            public Tiger(string latinName):base(latinName) {}
            public void Bite() {}
            public override string MakeSound() { return "Wraaau";}
        }
    

Lets add one other class:

        class Dog : SoundableAnimal
        {
            public Dog(string latinName):base(latinName) {}
            public void Bite() {}
            public override string MakeSound() { return "How How";}
        }
    

Now we have two classes of SoundableAnimal, but what is the main achievement? Look at below code:

        List loudyAnimals = new List();
        loudyAnimals.Add(new Tiger("Tigris"));
        loudyAnimals.Add(new Dog("Canis"));
        foreach (SoundableAnimal sa in loudyAnimals)
        {
            sa.MakeSound();
        }
    

This return:
Wraaau
How How

If the MakeSound function from SoundableAnimal wouldn't be virtual then in above example always would be called MakeSound function from base class, and result would be always the empty string. Now it is time to introduce second solution of this problem. Let's start from defining the interface.

    interface ISoundableAnimal
    {
        string MakeSound();
    }
    

Next we can change our both soundable animals classes:

    class Tiger : Animal, ISoundableAnimal
    {
        public Tiger(string latinName) : base(latinName) { }
        public void Bite() { }
        public  string MakeSound() { return "Wraaau"; }
    }

    class Dog : Animal, ISoundableAnimal
    {
        public Dog(string latinName) : base(latinName) { }
        public void Bite() { }
        public  string MakeSound() { return "How How"; }
    }
    

The superiority of the second solution is simplicity of the interface. We had to define only one method. The SoundableAnimal class have to have also constructor. Second adventages of this solution is posibility to multiple inheritance. We can inherit as many interfaces as we need. For class we can inherit only one base class.