面向对象编程中最重要的概念之一是继承。继承允许根据另一个类定义一个类,这样可以更容易地创建和维护应用程序。这也提供了重用代码并加快了代码的实现。
当创建一个类时,程序员可以指定这个新类应该继承现有类的哪些成员,而不是编写继承全部的数据成员和成员函数。这个现有的类称为基类,新类称为派生类或子类。
继承的想法实现了is-a(是一个什么类?)的关系。 例如,哺乳动物is是动物,狗is-a哺乳动物,因此也是狗is-a动物,等等。
类可以从多个类或接口派生,它可以从多个基类或接口继承数据和函数。
c# 中创建派生类,可使用如下语法:
<acess-specifier> class <base_class>
{
...
}
class <derived_class> : <base_class>
{
...
}
考虑有一个基类shape
及其派生类rectangle
,具体继承的实现详细如下:
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;
}
// derived class
class rectangle: shape
{
public int getarea()
{
return (width * height);
}
}
class rectangletester
{
static void main(string[] args)
{
rectangle rect = new rectangle();
rect.setwidth(10);
rect.setheight(20);
// print the area of the object.
console.writeline("total area: {0}", rect.getarea());
console.readkey();
}
}
}
当编译和执行上述代码时,会产生以下结果:
total area: 200
派生类继承基类成员变量和成员方法。 因此,在创建子类之前应该创建超类对象。您可以在成员初始化列表中给出超类初始化的说明或具体实现。
以下程序演示如何实现:
using system;
namespace rectangleapplication
{
class rectangle
{
//member variables
protected double length;
protected double width;
public rectangle(double l, double w)
{
length = l;
width = w;
}
public double getarea()
{
return length * width;
}
public void display()
{
console.writeline("length: {0}", length);
console.writeline("width: {0}", width);
console.writeline("area: {0}", getarea());
}
}//end class rectangle
class tabletop : rectangle
{
private double cost;
public tabletop(double l, double w) : base(l, w)
{ }
public double getcost()
{
double cost;
cost = getarea() * 70;
return cost;
}
public void display()
{
base.display();
console.writeline("cost: {0}", getcost());
}
}
class executerectangle
{
static void main(string[] args)
{
tabletop t = new tabletop(4.5, 7.5);
t.display();
console.readline();
}
}
}
当编译和执行上述代码时,会产生以下结果:
length: 4.5
width: 7.5
area: 33.75
cost: 2362.5
c# 不支持多重继承。但是,可以使用接口来实现多重继承。下面示例程序将演示如何实现:
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;
}
// base class paintcost
public interface paintcost
{
int getcost(int area);
}
// derived class
class rectangle : shape, paintcost
{
public int getarea()
{
return (width * height);
}
public int getcost(int area)
{
return area * 70;
}
}
class rectangletester
{
static void main(string[] args)
{
rectangle rect = new rectangle();
int area;
rect.setwidth(5);
rect.setheight(7);
area = rect.getarea();
// print the area of the object.
console.writeline("total area: {0}", rect.getarea());
console.writeline("total paint cost: ${0}" , rect.getcost(area));
console.readkey();
}
}
}
当编译和执行上述代码时,会产生以下结果: