演示具有多级继承的接口实现的 C# 程序
多级继承是将父类扩展到一个级别中的子类的过程。在这种类型的继承中,子类将继承父类,并且子类也充当创建的其他类的父类。例如,名为 P、Q 和 R 的三个类,其中类 R 派生自类 Q,类 Q 派生自类 P。
语法:
class P : Q
{
// Methods
}
接口指定一个类必须做什么而不是如何做。这是班级的蓝图。与类类似,接口也有方法、事件、变量等。但它只包含成员的声明。接口成员的实现将由隐式或显式实现接口的类给出。接口的主要优点是用来实现100%的抽象。
句法:
interface interface_name
{
//Method Declaration
}
在了解了多级继承和接口之后,现在我们用多级继承来实现接口。所以对此,我们可以将父类扩展为接口。
class GFG1 : interface1
{
// Method definition
public void MyMethod()
{
Console.WriteLine("Parent is called");
}
}
方法
- 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.
例子:
C#
// C# program to implement interface
// with multi-level inheritance
using System;
// Interface
interface interface1
{
// Method Declaration
void MyMethod();
}
// Parent class
class GFG1 : interface1
{
// Method definition
public void MyMethod()
{
Console.WriteLine("Hey! This is Parent");
}
}
// First child extends parent class
class GFG2 : GFG1
{
// Method definition
public void Method1()
{
Console.WriteLine("Hey! This is first child");
}
}
// Second child extends first child
class GFG3 : GFG2
{
// Method definition
public void Method2()
{
Console.WriteLine("Hey! This is second child");
}
}
class Geeks{
public static void Main(String[] args)
{
// Create an object for the second child
GFG3 obj = new GFG3();
// Call the methods of patent,
// first and second child classes
obj.MyMethod();
obj.Method1();
obj.Method2();
}
}
输出:
Hey! This is Parent
Hey! This is first child
Hey! This is second child