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

Here, we are going to learn how to inherit an abstract class and interface in the same class in C#?
Submitted by Nidhi, on October 14, 2020

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

Program:

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.






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.