C# program to implement hierarchical inheritance using the interface

Here, we are going to learn how to implement hierarchical inheritance using the interface in C#?
Submitted by Nidhi, on October 14, 2020

Here, we will implement hierarchical inheritance using the interface. In the hierarchical inheritance, one parent class is inherited by two child classes.

Program:

The source code to implement hierarchical inheritance using interfaces is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to demonstrate interface implementation 
//with hierarchical inheritance

using System;

interface MyInf
{
    //Method Declaration
    void Method1();
}

class Sample1 : MyInf
{
    //Method definition
    public void Method1()
    {
        Console.WriteLine("Method1() called");
    }
}

class Sample2 : Sample1
{
    //Method definition
    public void Method2()
    {
        Console.WriteLine("Method2() called");
    }
}

class Sample3 : Sample1
{
    //Method definition
    public void Method3()
    {
        Console.WriteLine("Method3() called");
    }
}

class Program
{
    public static void Main(String[] args)
    {
        Sample2 S2 = new Sample2();
        Sample3 S3 = new Sample3();

        S2.Method1();
        S2.Method2();

        S3.Method1();
        S3.Method3();
    }
}

Output:

Method1() called
Method2() called
Method1() called
Method3() called
Press any key to continue . . .

Explanation:

Here, we created an interface MyInf that contains the declaration of Method1(). Then we implemented the interface in the Sample1 class.  After that Sample1 class is inherited by Sample2 and Sample3 classes. The Sample2 and Sample3 classes also contain extra methods.

Now look to the Program class, It contains the Main() method, the Main() method is the entry point for the program. Here we created the objects of Sample2 and Sample3 classes. Then we called all methods that will print the corresponding message on the console screen.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.