C# Program to Demonstrate Interface Implementation with Multi-level Inheritance
Last Updated :
01 Nov, 2021
Multilevel Inheritance is the process of extending parent classes to child classes in a level. In this type of inheritance, a child class will inherit a parent class, and as well as the child class also act as the parent class to other class which is created. For example, three classes called P, Q, and R, where class R is derived from class Q and class Q, is derived from class P.
Syntax:
class P : Q
{
// Methods
}
Interface specifies what a class must do and not how. It is the blueprint of the class. Similar to a class, the interface also has methods, events, variables, etc. But it only contains 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. The main advantage of the interface is used to achieve 100% abstraction.
Syntax:
interface interface_name
{
//Method Declaration
}
After understanding the multilevel inheritance and interface now we implement the interface with the multilevel inheritance. So to this, we can extend the parent class to the interface.
class GFG1 : interface1
{
// Method definition
public void MyMethod()
{
Console.WriteLine("Parent is called");
}
}
Approach
- Create an Interface named “interface1” with method named “MyMethod”.
- Create a parent class named ‘GFG1″ by implementing an interface.
- Create first child class named “GFG2” by extending parent class.
- Create second child class named ” GFG3″ by extending first child class.
- Create an object in the main method.
- Access the methods present in all the classes using the object.
Example:
C#
using System;
interface interface1
{
void MyMethod();
}
class GFG1 : interface1
{
public void MyMethod()
{
Console.WriteLine( "Hey! This is Parent" );
}
}
class GFG2 : GFG1
{
public void Method1()
{
Console.WriteLine( "Hey! This is first child" );
}
}
class GFG3 : GFG2
{
public void Method2()
{
Console.WriteLine( "Hey! This is second child" );
}
}
class Geeks{
public static void Main(String[] args)
{
GFG3 obj = new GFG3();
obj.MyMethod();
obj.Method1();
obj.Method2();
}
}
|
Output:
Hey! This is Parent
Hey! This is first child
Hey! This is second child
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...