继承本质 重用代码 继承的思想实现了 属于 is-a的关系
* 继承的特点
* 1.派生类是对基类的扩展 派生类可以添加新的成员 但是不能移除已经继承的成员的定义
* 2.继承是可以传递的 如果C从B中派生 B又从A中派生 那么C不仅继承了B中声明的成员 同样也继承了A中声明的成员
* 3.构造函数和析构函数不能被继承 除此之外其他成员能被继承 基类中成员的访问方式只能决定派生类能否访问她们
* 4.派生类如果定义了与继承而来的成员同名的新成员 那么就可以覆盖已继承的成员 并不是删除这些成员 知识不再访问这些成员
* 5.类可以定义虚方法 虚属性 虚索引指示器 它的派生类能够重载这些成员 从而使类可以展示出多态性
* 6.派生类只能从一个类中继承 可以通过接口实现多重继承
* C#不支持多继承 可以使用接口实现多重继承 只支持单继承
使用接口实现多继承代码示例:
class Rectangle
{
protected int length;
protected int width;
public Rectangle()
{
Console.WriteLine("Rectangle::无参构造函数");
}
public Rectangle(int x, int y)
{
length = x;
width = y;
Console.WriteLine("Rectangle::参数化构造函数");
}
~Rectangle()
{
Console.WriteLine("~Rectangle()");
}
public int GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("长度:{0}", length);
Console.WriteLine("宽度:{0}", width);
Console.WriteLine("面积:{0}", GetArea());
}
}
public interface PaintArea
{
int getArea();
}
class CRetangle : Rectangle, PaintArea
{
protected int height;
public CRetangle()
{
Console.WriteLine("CRetangle::无参构造函数");
}
public CRetangle(int x = 0, int y = 0, int z = 0) : base(x, y)
{
height = z;
Console.WriteLine("CRetangle::参数化构造函数");
}
~CRetangle()
{
Console.WriteLine("~CRectangle()");
}
public int GetVolume()
{
return GetArea() * height;
}
public int getArea()
{
return 100;
}
public void Display()
{
Console.WriteLine("长度:{0}", length);
Console.WriteLine("宽度:{0}", width);
Console.WriteLine("面积:{0}", GetArea());
Console.WriteLine("体积:{0}", GetVolume());
Console.WriteLine("接口:{0}", getArea());
}
}