扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
抽象类将一个(或多个)方法或属性声明为抽象的。这样的方法并不具有声明它们的类中提供的实现,尽管抽象类也可以包含非抽象方法,也就是说,已经为其方法提供了实现。抽象类不能直接实例化,而只能作为派生类。这样的派生类必须为所有的抽象方法和属性提供实现(使用 override 关键字),除非派生成员本身被声明为抽象的。
下面的示例声明了一个抽象的 Employee 类。我们还创建了一个名为 Manager 的派生类,它提供了定义在 Employee 类中的抽象方法 show() 的实现:
using System;
public abstract class Employee
{
// abstract show method
public abstract void show();
}
// Manager class extends Employee
public class Manager: Employee
{
string name;
public Manager(string name)
{
this.name = name;
}
//override the show method
public override void show()
{
Console.WriteLine("Name : " + name);
}
}
public class CreateManager
{
public static void Main(string[] args)
{
// Create instance of Manager and assign it to an Employee reference
Employee temp = new Manager("John Chapman");
// Call show method. This will call the show method of the Manager class
temp.show();
}
}
这段代码调用了由 Manager 类提供的 show() 实现,并且在屏幕上打印出雇员的名字。
查看本文来源如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。