引言:
在面向对象语言中,接口的多种不同的实现方式即为多态。引用Charlie Calverts对多态的描述——多态性是允许你将父对象设置成为一个或更多的他的子对象相等的技术,赋值之后,父对象就可以根据当前赋值给它的子对象的特性以不同的方式运作(摘自“Delphi4 编程技术内幕”)。简单的说,就是一句话:允许将子类类型的指针赋值给父类类型的指针。多态性在Object Pascal和C++中都是通过虚函数实现的。
/*测试类:
根据用户选择下车,计算总租金并输出总租金。 */
class Vehicle{
String brand;
String carId;
public Vehicle(){
}
public Vehicle(String brand,String carId){
this.brand=brand;
this.carId=carId;
}
public double getSumRent(int days){
return 0;
}
}
class Car extends Vehicle{
String carType = “两厢” ;
//构造方法
public Car(){
}
public Car(String carType,String brand,String carId){
super(brand,carId);
this.carType = carType;
}
public double getSumRent(int days){
switch(carType){
case "两厢":
return 300*days;
case "三厢":
return 350*days;
default :
return 500*days;
}
}
}
class Bus extends Vehicle{
int seatNum;
//构造方法
public Bus(){
}
public Bus(int seatNum,String brand,String carId){
super(carId,brand);
this.seatNum = seatNum;
}
//计算总佣金的方法
public double getSumRent(int days){
if(seatNum <= 16){
return 400 * days;
}else{
return 600 * days;
}
}
}
class VehicleTest{
public static void main(String[] args){
//Car car = new Car(“三厢”,“五菱”,“中华”);
//System.out.println(car.getSumRent(5));
// System.out.println();
// bus = new Bus(15,“五菱”,“中华”);
// System.out.println(bus.getSumRent(6));
Vehicle v = new Car();
//System.out.println(v.getSumRent(5));
v=new Bus(15,“五菱”,“中华”);
System.out.println(v.getSumRent(6));
v = new Car(“三厢”,“五菱”,“中华”);
System.out.println(v.getSumRent(5));
}
}