程序清单:
using System
class Vehicle //定义汽车类
{
int wheels;//公有成员:轮子个数
protected float weight; //保护成员:重量
public Vehicle(){;}
public Vehicle(int w,float g){
wheels = w;
weight = g;
}
public void Speak(){
Console.WriteLine("the w vehicle is speaking!");
}
};
class Car:Vehicle //定义轿车类:从汽车类中继承
{
int passenger; //私有成员:乘客数
public Car(int w,float g,int p):base(w,g)
{
wheels = w;
weight = g;
passengers = p;
}
}
类Car继承了Vehicle的Speak()方法。在这里可以给Car类也声明一个Speak()方法,覆盖Vehicle中的Speak,见下面的代码:
using System;
class Vehicle//定义汽车类
{
public int wheels;//公有成员:轮子个数
protected float weight; //保护成员:重量
public Vehicle(){;};
public Vehicle(int w,float g){
wheels = w;
weight = g;
}
public void Speak(){
Console.WriteLIne("the w vehicle is speaking!");
}
}
class Car:Vehicle//定义轿车类
{
int passengers;//私有成员:乘客数
public Car(int w,float g,int p){
wheels = w;
weight = g;
passengers = p;
}
new public void Speak(){
Console.WriteLine("Di-di!");
}
}
注意:如果在成员声明中加了new关键字修饰符,而该成员事实上并没有覆盖继承的成员,编译器将会给出警告。在一个成员声明同时使用new和override 则编译器会报告错误。
|
|