1.什么是继承
2.继承有什么用
3.怎么用继承
概念:当创建一个类时,程序员不需要完全重新编写新的数据成员和成员函数,只需要设计一个新的类,继承了已有的类的成员即可,这个已有类被称为的基类,这个新的类被称为派生类
继承的思想实现了属于(IS-A)关系。例如,哺乳
物属于(IS-A)动物,够属于(IS-A)哺乳动物,一次狗属于(IS-A)动物
继承有什么用:当创建一个类时,程序员不需要完全重新编写新的数据成员和成员函数,只需要设计一个新的类,继承了已有的类的成员即可,这个已有类被称为的基类,这个新的类被称为派生类.
怎么用继承:
//语法
<访问修饰符符> class <基类>
{
...
}
class <派生类> : <基类>
{
...
}
多重继承(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;
}
// 基类 PaintCost
public interface PaintCost
{
int getCost(int area);
}
// 派生类
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();
// 打印对象的面积
Console.WriteLine("总面积: {0}", Rect.getArea());
Console.WriteLine("油漆总成本: ${0}" , Rect.getCost(area));
Console.ReadKey();
}
}
}
tip:
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);
}
public int getCost(int area)
{
return area * 70;
}
}
class RectangleTester
{
static void Main(string[] args)
{
Shape Rect = new Rectangle();//--------若使用单继承则可用变量名前面可以基类名,若多重继承则只能用new出来的类型
int area;
Rect.setWidth(5);
Rect.setHeight(7);
// area = Rect.getArea();
// 打印对象的面积
// Console.WriteLine("总面积: {0}", Rect.getArea());
// Console.WriteLine("油漆总成本: ${0}" , Rect.getCost(area));
Console.ReadKey();
}
}
}