代码如下:
Vehicle类:
public class Vehicle {
//返回总租金
public double getSumRent(int days) {
return 0;
}
}
Car类:
/*
* Car:小轿车类是Vehicle的子类,属性:车型(两厢,三厢,越野)
* 两厢:每天300;三厢:每天350;越野:每天500
*/
public class Car extends Vehicle {
String motorType; //车型
@Override
public double getSumRent(int days) {
switch (motorType) {
case "两厢":
return 300*days;
case "三厢":
return 350*days;
case "SUV":
return 500*days;
}
return 0;
}
}
Bus类:
/*
* Bus:多座汽车,属性:座位数
* 座位数<=16:每天600
* 座位数>16:每天800
*/
public class Bus extends Vehicle {
int seatNum;
@Override
public double getSumRent(int days) {
if(seatNum>16)
return 800*days;
return 600*days;
}
}
测试Demo类:
import java.util.Scanner;
/*
* 根据用户选择不同的汽车,计算总租金并输出总租金
*/
public class Demo {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请选择汽车类型:");
System.out.println("\t 1 Car \t2 Bus");
int vehicleType=sc.nextInt();
if(vehicleType==1) {
//选择了Car
System.out.println("继续选择:");
System.out.println("\t1两厢\t2三厢\t3SUV");
int carType=sc.nextInt();
//创建一个Car类型对象
Car myCar=new Car();
//根据用户的选择设置小汽车的类型
switch (carType) {
case 1:
myCar.motorType="两厢";
break;
case 2:
myCar.motorType="三厢";
break;
case 3:
myCar.motorType="SUV";
break;
default:
myCar.motorType="三厢";
break;
}
System.out.println("请输入想租的天数:");
int days=sc.nextInt();
System.out.println("租金为:"+myCar.getSumRent(days));
}
else if(vehicleType==2) {
//选择了Bus
System.out.println("请选择多座汽车的座位数:");
System.out.println("\t1小于16座\t2大于16座");
int seatsNum=sc.nextInt();
//创建Bus对象
Bus myBus=new Bus();
myBus.seatNum=seatsNum;
System.out.println("请输入想租的天数:");
int days=sc.nextInt();
System.out.println("租金为:"+myBus.getSumRent(days));
}
}
}