C# 抽象
抽象类和抽象方法
数据抽象是隐藏某些详细信息而仅向用户显示必要信息的过程。
抽象可以通过抽象类或接口来实现(下一章将详细介绍)。
abstract
关键字用于类和方法
- 抽象类:是一个受限类,不能用于创建对象(要访问它,必须从另一个类继承)。
- 抽象方法:只能在抽象类中使用,并且它没有方法体。方法体由派生类(继承自)提供。
抽象类可以同时拥有抽象方法和常规方法
abstract class Animal
{
public abstract void animalSound();
public void sleep()
{
Console.WriteLine("Zzz");
}
}
从上面的示例来看,不可能创建 Animal 类的对象
Animal myObj = new Animal(); // Will generate an error (Cannot create an instance of the abstract class or interface 'Animal')
要访问抽象类,必须从另一个类继承。让我们将我们在多态性章节中使用的 Animal 类转换为抽象类。
还记得在继承章节中,我们使用 :
符号来继承类,并使用 override
关键字来重写基类方法。
示例
// Abstract class
abstract class Animal
{
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep()
{
Console.WriteLine("Zzz");
}
}
// Derived class (inherit from Animal)
class Pig : Animal
{
public override void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound(); // Call the abstract method
myPig.sleep(); // Call the regular method
}
}