演示抽象类继承的 C# 程序
抽象是隐藏内部细节并仅显示功能的过程。 abstract 关键字用在类或方法之前,以将类或方法声明为抽象。继承是一种面向对象的编程方法,允许一个类继承另一个类的特性(字段和方法)。在 C# 中,我们还可以使用 :运算符继承抽象类。
abstract class Abstract_class
{
// Method declaration for abstract class
public abstract void abstract_method();
}
class class_name : Abstract_class
{
// Method definition for abstract method
}
方法:
- Create an abstract class and declare a method inside it using abstract keyword.
- Create a parent class by overriding the method of an abstract class.
- Create first child class that inherits the parent class and define a method inside it.
- Create an object that is “Geeks1 obj = new Geeks1()” for the first child class in the main method.
- Call all the methods that are declared using obj object.
例子:
C#
// C# program to inherit abstract class.
using System;
// Abstract class
abstract class Abstract_class
{
// Method Declaration for abstract class
public abstract void abstract_method();
}
// Parent class
class Geeks : Abstract_class
{
// Method definition for abstract method
public override void abstract_method()
{
Console.WriteLine("Abstract method is called");
}
}
// First child class extends parent
class Geeks1 : Geeks
{
// Method definition
public void method1()
{
Console.WriteLine("method-1 is called");
}
}
class GFG{
// Driver code
public static void Main(String[] args)
{
// Create an object
Geeks1 obj = new Geeks1();
// Call the methods
obj.abstract_method();
obj.method1();
}
}
输出:
Abstract method is called
method-1 is called