首页 > IT职业 > IT图书 > java入门第二季--达达租车系统1.0版本
租车系统简要分析:
(1)定义一个父类:车辆Vehicle
(2)定义三个子类用于继承父类:载人的客车类Car,载货的卡车类Truck,既能载人又能载货的类CarryTwo
(3)共性:名称,租金。所以Vehicle类定义两个成员变量即可。
父类Vehicle代码如下:
class Vehicle{
private String name; //名称
private int rent; //租金
public Vehicle(String name,int rent){
this.name = name;
this.rent = rent;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getRent(){
return rent;
}
public void setRent(int rent){
this.rent = rent;
}
} 客车类Car
class Car extends Vehicle{
private int number; //载人的人数
public Car(String name,int rent,int number){
super(name,rent);
this.number = number;
}
public int getNumber(){
return number;
}
public void setNumber(int number){
this.number = number;
}
public String toString(){
return ((this.getName())+"t"+(this.getRent())+"t"+("载人:"+number+"人"));
}
} super(name,rent); 通过super关键字调用父类的构造方法。其他子类也是如此。
载货的卡车类:Truck
class Truck extends Vehicle{
private int weight; //载货的重量
public Truck(String name,int rent,int weight){
super(name,rent);
this.weight = weight;
}
public int getWeight(){
return weight;
}
public void setWeight(int weight){
this.weight = weight;
}
public String toString(){
return ((this.getName())+"t"+(this.getRent())+"t"+("载货:"+weight+"吨"));
}
} 既可载人又可载货的类:CarryTwo
class CarryTwo extends Vehicle{
private int number; //载人的人数
private int weight; //载货的重量
public CarryTwo(String name,int rent,int number,int weight){
super(name,rent);
this.number = number;
this.weight = weight;
}
public int getNumber(){
return number;
}
public void setNumber(int number){
this.number = number;
}
public int getWeight(){
return weight;
}
public void setWeight(int weight){
this.weight = weight;
}
public String toString(){
return ((this.getName())+"t"+(this.getRent())+"t"+"载人:"+number+"人"+" 载货:"+weight+"吨");
}
} 因为CarryTwo继承与Vehicle,Vehicle类没有成员变量number和weight。虽然在Car类定义了number,在Truck类定义了weight。但是由于是私有的,CarryTwo无法访问。
最后定义一个测试类Test,用于演示结果
import java.util.Scanner;
class Test {
public static void main(String[] args) {
System.out.println("======欢迎使用达达租车系统======");
System.out.print("你是否需要租车(1是,0否):");
Vehicle v[] = {new Car("奥迪A6",500,4),
new Car("宝马X6",600,5),
new CarryTwo("皮卡雪6",450,2,3),
new Car("金龙",800,20),
new Truck("松花江",500,6),
new Truck("依维柯",1000,20)};
//判断用户输入是否正确
while(true){
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
System.out.println();
if(i==1){
System.out.println("你可以选择租车的类型及其价目表:");
break;
}
else if(i==0){
System.out.println("欢迎再次使用!");
break;
}
else {
System.out.print("输入有误,请重新输入:");
continue;
}
}
System.out.println("序号"+" "+"汽车名称"+" "+"租金(元/天)"+" "+"容量");
//显示所有可租的车辆
int id = 1; //序号从1开始
for(;id5){
System.out.println("不好意思,一次最多只能租5辆车");
continue;
}else{
for(int i=1;i (Car)v[id-1]为向下转型;可以与强制转换结合联想
运行结果如图所示:
改程序基本上完成了需求,有些地方和运行界面还是做得不是很好,有待改善。以上代码如有疑惑,共同研究。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3451/viewspace-2799318/ ,如需转载,请注明出处,否则将追究法律责任。