C#中的抽象类
C#中的抽象类包括抽象和非抽象方法。一个类被声明为abstract是抽象类。您不能实例化一个抽象类。
让我们看一个例子,其中有一个抽象类Vehicle和抽象方法display()
-
public abstract class Vehicle { public abstract void display(); }
抽象类具有派生类:公共汽车,汽车和摩托车。以下是Bus派生类的实现-
public class Bus : Vehicle { public override void display() { Console.WriteLine("Bus"); } }
示例
让我们看看C#中抽象类的完整示例-
using System; public abstract class Vehicle { public abstract void display(); } public class Bus : Vehicle { public override void display() { Console.WriteLine("Bus"); } } public class Car : Vehicle { public override void display() { Console.WriteLine("Car"); } } public class Motorcycle : Vehicle { public override void display() { Console.WriteLine("Motorcycle"); } } public class MyClass { public static void Main() { Vehicle v; v = new Bus(); v.display(); v = new Car(); v.display(); v = new Motorcycle(); v.display(); } }
输出结果
Bus Car Motorcycle