父類:MotoVehicle
public abstract class MotoVehicle {
String no;
String brand;
String color;
String mileage;
int days;
public abstract float CalcRent(int days); }
子類1:Car
public final class Car extends MotoVehicle {
String type;
@Override
public float CalcRent(int days) {
float rent = 0;
if(type.equals("別克商務艙GL8")){
rent = 600*days;
}else if(type.equals("寶馬550i")){
rent = 500*days;
}else if(type.equals("別克林蔭大道")){
rent = 300*days;
}
return rent;
}
public Car() {
super();
}
public Car(String type) {
super();
this.type = type;
}
}
子類2:Bus
public final class Bus extends MotoVehicle {
int seatcount;
@Override
public float CalcRent(int days) {
float rent = 0;
if(seatcount<=16){
rent = 800*days;
}else{
rent = 1500*days;
}
return rent;
}
public Bus() {
super();
}
public Bus(int seatcount) {
super();
this.seatcount = seatcount;
}
}
測試類:MotoVehicleText
import java.util.Scanner;
public class MotoVehicleText {
public static void main(String[] args) {
String kind;
float rent = 0;
Scanner input = new Scanner(System.in);
System.out.println("請輸入租車的種類");
kind = input.next();
if(kind.equals("car")){
Car a = new Car();
System.out.println("請輸入租車時間:");
a.days = input.nextInt();
System.out.println("請輸入租車的型號:");
a.type = input.next();
rent = a.CalcRent(a.days);
}else if(kind.equals("bus")){
Bus b = new Bus();
System.out.println("請輸入租車時間:");
b.days = input.nextInt();
System.out.println("請輸入租車的座位數:");
b.seatcount = input.nextInt();
rent = b.CalcRent(b.days);
}
System.out.println("您的租車費用為"+rent);
input.close();
}
}