继承使我们可以用另一个类来定义一个类,这使创建和维护应用程序变得更加容易。
创建类时,程序员可以指定新类继承现有类的成员,而不必编写全新的数据成员和成员函数。此现有类称为基类,而新类称为派生类。一个类可以从一个以上的类或接口派生,这意味着它可以从多个基类或接口继承数据和函数。
让我们看一个例子-
using System;
namespace InheritanceApplication {
class Shape {
public void setWidth(int w) {
width = w;
}
public void setHeight(int h) {
height = h;
}
protected int width;
protected int height;
}
//派生类
class Rectangle: Shape {
public int getArea() {
return (width * height);
}
}
class Demo {
static void Main(string[] args) {
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
//打印对象的区域。
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.ReadKey();
}
}
}输出结果
Total area: 35