虽然很多地方可以见到这个例子,但还是忍不住贴出来,供大家尤其是新学者参考一下!这个例子不止是继承方面的好例子,而且两个Set和Get方法的使用也值得我们借签!
namespace CAR
{
public class Car//class of car,has attribute of 'weight' and 'speed'
{
private int weight;
private int speed;
public Car(int Weight,int Speed)
{ //相当公共属性
weight=Weight;
speed=Speed;
}
public void setweight(int Weight)
{
weight=Weight;
}
public void setspeed(int Speed)
{
speed=Speed;
}
public int getspeed()
{
return speed;
}
public int getweight()
{
return weight;
}
};
public class Sportcar:Car //inherit class of Car,has attributes of 'weight','speed','color' 运动车继承了车的属性,包括重量、速度、颜色
{
private string color;
public Sportcar(int Weight,int Speed,string Color):base(Weight,Speed)
{
setweight(Weight);
setspeed(Speed);
color=Color;
}
public void setcolor(string Color)
{
color=Color;
}
public string getcolor()
{
return color;
}
public static void Main()
{
Car car=new Car(100,100);
Sportcar sportcar=new Sportcar(100,200,"blcak");
Console.WriteLine("car's weight is "+car.getweight());
Console.WriteLine("car's speed is "+car.getspeed());
Console.WriteLine("sportcar's weight is "+sportcar.getweight());
Console.WriteLine("sportcar's speed is "+sportcar.getspeed());
Console.WriteLine("sportcar's speed is "+sportcar.getcolor());
}
}
}
[此贴子已经被作者于2007-5-16 9:38:55编辑过]