Sunday, February 18, 2018

Class Inheritance

Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective employment of reuse, you can save time in your programming.


Create BaseClass.cs


using System;

public class ParentClass
{
    public ParentClass()
    {
        Console.WriteLine("Parent Constructor.");
    }

    public void print()
    {
        Console.WriteLine("I'm a Parent Class.");
    }
}

public class ChildClass : ParentClass
{
    public ChildClass()
    {
        Console.WriteLine("Child Constructor.");
    }

    public static void Main()
    {
        ChildClass child = new ChildClass();

        child.print();
    }
}
Output:
Parent Constructor.
Child Constructor.
I'm a Parent Class.
Shows two classes. The top class is named ParentClass and the main class is called ChildClass. What we want to do is create a child class, using existing code from ParentClass.
First we must declare our intention to use ParentClass as the base class of ChildClass. This is accomplished through the ChildClassdeclaration public class ChildClass : ParentClass. The base class is specified by adding a colon, “:”, after the derived class identifier and then specifying the base class name.
Note: C# supports single class inheritance only. Therefore, you can specify only one base class to inherit from. However, it does allow multiple interface inheritance, a subject covered in a later lesson.
ChildClass has exactly the same capabilities as ParentClass. Because of this, you can also say ChildClass “is” a ParentClass. This is shown in the Main() method of ChildClass when the print() method is called. ChildClass does not have its own print() method, so it uses theParentClass print() method. You can see the results in the 3rd line of output.
Base classes are automatically instantiated before derived classes. Notice the output from Listing . The ParentClass constructor executed before the ChildClass constructor.
Thank you

No comments:

Post a Comment