Inheritance

Inheritance allows a class to absorb or inherit all the properties and methods of another class. It is like a parent-child relationship where the child inherits some properties from his/her parents such as facial features and attitudes. The base class or the parent class, is the class which is inherited by other classes. The derived class or the child class, is the one inheriting from the base class. All the methods and properties of the base class can be used by the derived class except for the private members and methods. We will soon discover that all the classes in the .NET Framework inherits the Object class. We will demonstrate the basic concept of inheritance in the following example program. Create a seperate class file and write the following code.

using System;
 
namespace InheritanceDemo
{
    class Parent
    {
        private string message;
 
        public string Message
        {
            get { return message; }
            set { message = value; }
        }
 
        public void ShowMessage()
        {
            Console.WriteLine(message);
        }
 
        public Parent(string message)
        {
            this.message = message;
        }
    }
 
    class Child : Parent
    {
        public Child(string message)
            : base(message)
        {
 
        }
    }
}

Example 1 – Inheritance Demo

We defined two classes named Parent and Child. We include a  private data member (line 7) and its corresponding publicproperty(lines 9-13). We also defined a method that will show the message. A constructor was defined for the Parent class that accepts a string argument that will serve as the message. Now take a look at the Child class  (line 26). It inherits the Parent class and absorbs all its methods and properties. The syntax for inheriting a class is as follows.

class DerivedClass : BaseClass

You simply place a colon (:) after the name of the class and then indicate the class that it will inherit. Inside the Child class is a single constructor that also accepts a string argument. When creating inherited classes, both the derived class constructor and the base class default constructor are executed. A default constructor is a no-parameter constructor. If no constructor was defined in a class, the compiler automatically creates a default constructor.

If we want to call the base class constructor when we call the derived class contructor, we need to use the base keyword. The basekeyword calls a constructor of the base class. We need to write a colon before using the base keyword. By supplying the value of the message parameter of the derived class constructor and passing it inside the parentheses of the base keyword, it will call the matching contructor of the base class and pass the value of the message. The Parent‘s class constructor will then assign the value of the message into its private data member. You can add some code inside the body of the Child contructor and it will be executed after the Parent‘s constructor. If we omit the base keyword, the default constructor of the base class will be called instead.

Let’s now create the actual Parent and Child objects to demonstrate that Child really inherits the methods and properties of the Parent class.

namespace InheritanceDemo
{
    class Program
    {
        static void Main()
        {
            Parent myParent = new Parent("Message from parent.");
            Child myChild = new Child("Message from child.");
 
            myParent.ShowMessage();
 
            myChild.ShowMessage();
 
            myParent.Message = "Modified message of the parent.";
            myParent.ShowMessage();
 
            myChild.Message = "Modified message of the child.";
            myChild.ShowMessage();
 
            //myChild.message; ERROR: can't access private members of base class
        }
    }
}

Example 2 – Inheritance in Action

Message from parent.
Message from child.
Modified message of the parent.
Modified message of the child.

We intialized both objects using their respective constructors (line 7-8). We then show the use of inheritance by accessing the methods and members of the Parent class through a Child object. Even if the Child class inherits from the Parent class, the  private members of the Parent class is still inaccessible to the Child class  (line 20). You will be introduced to the protected access specifier in the next lesson which allows you to access the members and methods of the base class.

Another thing to note. If another class inherits the Child class, that class will inherit all the methods and properties that the Child class inherits from the parent class.

class GrandChild : Child
{
   //Empty Body
}

The class has nothing inside its body. When you create a GrandChild class and call a property from the Parent class, you will receive no error and the operation you are trying to do will be successful. Note that no constructor that accepts a string argument was defined inside the GrandChild therefore, you can only use the parameterless or default constructor.

GrandChild myGrandChild = new GrandChild(); 

myGrandChild.Message = "Hello my grandchild!";
myGrandChild.ShowMessage();

When we create the class and call the GrandChild‘s constructor, the Parent‘s class constructor is called first. Next, the Child‘s constructor is called afterwards. Finally, the GrandChild‘s constructor is executed. The program below shows the proper order of constructor execution. Again, I place the classes into a separate code file for readability.

using System;
 
namespace InheritanceDemo
{
    class Parent
    {
        public Parent()
        {
            Console.WriteLine("Parent constructor was called!");
        }
    }
 
    class Child : Parent
    {
        public Child()
        {
            Console.WriteLine("Child constructor was called!");
        }
    }
 
    class GrandChild : Child
    {
        public GrandChild()
        {
            Console.WriteLine("GrandChild constructor was called!");
        }
    }
 
    class Program
    {
        static void Main()
        {
            GrandChild myGrandChild = new GrandChild();
        }
    }
}

Example 3 – Proper Order of Execution of Constructors

Parent constructor was called!
Child constructor was called!
GrandChild constructor was called!

Written by compitionpoint

Leave a Comment

Your email address will not be published. Required fields are marked *