抽象和封装是面向对象编程中的相关功能。抽象使相关信息可见,封装使程序员能够实现所需的抽象级别。
可以使用C#中的抽象类来实现抽象。C#允许您创建用于提供接口的部分类实现的抽象类。当派生类从其继承时,实现完成。抽象类包含抽象方法,这些方法由派生类实现。派生类具有更特殊的功能。
以下是一些关键点-
您不能创建抽象类的实例
您不能在抽象类之外声明抽象方法
当一个类被声明为密封的时,它不能被继承,抽象类也不能被声明为密封的。
using System;
namespace Demo {
abstract class Shape {
public abstract int area();
}
class Rectangle: Shape {
private int length;
private int width;
public Rectangle( int a = 0, int b = 0) {
length = a;
width = b;
}
public override int area () {
Console.WriteLine("矩形类区域:");
return (width * length);
}
}
class RectangleTester {
static void Main(string[] args) {
Rectangle r = new Rectangle(20, 15);
double a = r.area();
Console.WriteLine("Area: {0}",a);
Console.ReadKey();
}
}
}输出结果
矩形类区域: Area: 300