继承是面向对象程序设计中最重要的概念之一。继承允许我们通过一个类来定义另一个类,这使得创建和维护一个程序变得简单,同时也减少了代码量和开发时间。
当创建一个类时,程序员不需要完全重新编写新的数据成员和成员函数,只需设计一个新的类,继承了已有的类的成员即可。这个已有的类被称为基类,这个新的类被称为派生类。
基类和派生类
一个类可以派生自多个类或接口,这意味着它可以从多个基类或接口继承数据和函数。
//C#继承
using System;
namespace InheritanceApplication
{
class Shape
{
protected int length;
protected int width;
public void setLength(int len)
{
length = len;
}
public void setWidth(int wid)
{
width = wid;
}
}
class Rectange:Shape
{
public int getArea()
{
return width*length;
}
}
class RectangleTest
{
public static void Mian(string[] args)
{
Rectange r1 = new Rectange();
r1.setWidth(6);
r1.setLength(7);
Consle.WriteLine("r1's Area is:{0}",r1.getArea());
Consle.ReadKey();
}
}
}
基类的初始化
派生类继承了基类的成员变量和成员方法。因此父类对象在子类对象创建之前创建。可以在成员初始化列表中进行父类的初始化。
//C#基类的初始化
using System;
namespace InheritanceApplication
{
class Shape
{
protected double width;
protected double length;
public Shape(double wid,double len)
{
width = wid;
length = len;
}
public double getArea()
{
return width*length;
}
public void Display()
{
Consle.WriteLine("Width:{0}",width);
Consle.WriteLine("Length:{0}",length);
Consle.WriteLine("Area:{0}",getArea());
}
}
class Rectange:Shape
{
private double cost;
public Rectange(double w,double l):base(w,l)
{}
public void getCost()
{
double cost;
cost = getArea() * 80;
return cost;
}
public void Display()
{
base.Display();
Consle.WriteLine("cost:{0}",getCost);
}
}
class RectangeTest
{
public static void Mian(stirng[] args)
{
Rectange r1 = new Rectange(6.0,7.0);
r1.Display();
Consle.ReadLine();
}
}
}
C#多重继承
多重继承指的是一个类别可以同时从多于一个父类继承行为与特征的功能。与单一继承相对,单一继承指一个类别只可以继承自一个父类,
C#不支持多重继承。但是可以通过接口来实现多重继承。
//C#多重继承
using System;
namespace InheritanceApplication
{
class Shape
{
protected int width;
protected int lenght;
public int setWidth(int wid)
{
width = wid;
}
public int setLength(int len)
{
lenght = len;
}
}
public interface PointCost
{
public int getCost(int area);
}
class Recx:Shape,PointCost
{
public int getArea()
{
return width*lenght;
}
public int getCost(int area)
{
return area*70;
}
}
class RecxTest
{
public static void Mian(string[] args)
{
Rexc r1 = new Recx();
int area;
r1.setWidth(7);
r1.setLength(8);
area = r1.getArea();
int cost = r1.getCost(area);
Consle.WriteLine("area:{0}",area);
Consle.WriteLine("cost:{0}",cost);
Consle.ReadLine();
}
}
}