C# Program to Inherit an Abstract Class and Interface in the Same Class
Last Updated :
15 Nov, 2021
Abstract Class is the way to achieve abstraction. It is a special class that never be instantiated directly. This class should contain at least one abstract method in it and mark by abstract keyword in the class definition. The main purpose of this class is to give a blueprint for derived classes and set some rules what the derived classes must implement when they inherit an abstract class. An abstract class can be used as a base class and all derived classes must implement the abstract definitions.
Syntax:
abstract class classname
{
// Method Declaration in abstract class
}
Here, the classname is the name of an abstract class. We can declare any number of methods inside it.
Interface is like a class, it can also have methods, properties, events, and indexers as its members. But interfaces can only have the declaration of the members. The implementation of the interface’s members will be given by the class that implements the interface implicitly or explicitly. Or we can say that it is the blueprint of the class.
Syntax:
interface interface_name
{
// Method Declaration in interface
}
Now given that one interface and one abstract class, now our task is to inherit both interface and abstract class in the same class.
Approach:
- Create an abstract class using abstract keyword and write a method definition for the abstract method.
- Create an interface using the interface keyword and write a method definition for Interface.
- Create a class with name GFG that will inherit both abstract class and interface like this:
class GFG : Abstract_Class, Interface
{
// Method definition for abstract method
// Method definition for interface
}
- Write the method definitions for both abstract class and interface in the GFG class.
- Inside the main, create two objects for both abstract class and interface.
- Call the methods using those objects and display the output.
Example:
C#
using System;
abstract class Abstract_Class
{
public abstract void abstract_method();
}
interface Interface
{
void interface_method();
}
class GFG : Abstract_Class, Interface
{
public override void abstract_method()
{
Console.WriteLine( "I am the method of abstract class" );
}
public void interface_method()
{
Console.WriteLine( "I am the method of interface" );
}
}
class Geeks{
public static void Main(String[] args)
{
Abstract_Class ac = new GFG();
Interface inf = new GFG();
ac.abstract_method();
inf.interface_method();
}
}
|
Output:
I am the method of abstract class
I am the method of interface
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...