之前的答答租车系统虽然可以实现项目的要求,但是没有用Java面向对象,今天用面向对象的三大特性封装、继承和多态来改进原来的代码。题目和之前的代码参考上篇博客,这里不再述说。
改进后的代码:
Vehicle.java
/*车的父类,包含:
车名和租金两个私有属性name和rent;
访问属性的对应方法setter和getter;
带参数的构造方法;
打印属性值的方法Display();
*/
public class Vehicle {
private String name; //车名
private int rent; //租金
public Vehicle(String name, int rent) {
this.name = name;
this.rent = rent;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setRent(int rent) {
this.rent = rent;
}
public int getRent() {
return rent;
}
public void Display(int num) {
System.out.println(num + " " + this.getName() +
" " + this.getRent());
}
}
Cars.java
/*汽车类,车的子类,包含:
父类继承的属性和方法;
新添加的私有属性载人数seatingCapacity;
seatingCapacity对应的访问方法;
Display()方法的重写;
含参构造方法;
*/
public class Cars extends Vehicle {
private int seatingCapacity; //载人量
public Cars(String name, int rent, int seatingCapacity) {
super(name, rent); //父类构造方法带参数,要用super显示调用
this.setName(name);
this.setRent(rent);
this.seatingCapacity = seatingCapacity;
}
public int getSeatingCapacity() {
return seatingCapacity;
}
public void Display(int num) {
System.out.println(num + " " + this.getName() +
" " + this.getRent() + " " +
"载人:" + seatingCapacity + "人" + " ");
}
}
Trucks.java
/*卡车类,车的子类,包含:
父类继承的属性和方法;
新添加的私有属性载货数cargoCapacity;
cargoCapacity对应的访问方法;
Display()方法的重写;
含参构造方法
*/
public class Trucks extends Vehicle {
private int cargoCapa