C# - Inherit an Abstract Class and Interface in Same Class

In this example, we will learn how to inherit an abstract class and interface in the same class using C# program?
Submitted by Nidhi, on October 14, 2020 [Last updated : March 21, 2023]

In this program, we inherit the abstract method of abstract class and interface method in the same class.

C# program to inherit an abstract class and interface in the same class

The source code to inherit an abstract class and interface in the same class is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to inherit an abstract class 
//and interface in the same class

using System;

abstract class Abs
{
    //Method Declaration
    public abstract void Method1();
}

interface Inf
{
    //Method Declaration
    void Method2();
}

class Sample : Abs, Inf
{
    //Method definitions
    public override void Method1()
    {
        Console.WriteLine("Method1() called");
    }
    public void Method2()
    {
        Console.WriteLine("Method2() called");
    }
}

class Program
{
    public static void Main(String[] args)
    {
        Abs M1;
        Inf M2;

        M1 = new Sample();
        M2 = new Sample();

        M1.Method1();
        M2.Method2();
    }
}

Output

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

Explanation

Here, we created an interface Inf and an abstract class Abs. The abstract class Abs contains a declaration of Method1() and the interface Inf contains a declaration of Method2(). Then we inherited the abstract class and interface in the Sample class.

Now look to the Program class that contains the Main() method. The Main() method is the entry point for the program. In the Main() method, we created the reference of abstract class and interface, both are initialized by the object of the Sample class. After that, we called Method1() and Method2() that will print appropriate messages on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.