父类
// 抽象方法
// 抽象类 abstract
public abstract class Vehicle {
private String no;
private String brand;
private String color;
private float mileage;
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public float getMileage() {
return mileage;
}
public void setMileage(float mileage) {
this.mileage = mileage;
}
// 必须有一个空构造方法
public Vehicle() {
super();
}
public Vehicle(String no) {
super();
this.no = no;
}
// 抽象方法 abstract
// 抽象类
public abstract float calRent(int day);
}
子类
public class Car extends Vehicle {
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Car() {
super();
}
public Car(String no, String type) {
super(no);
this.type = type;
}
public float calRent(int days) {
switch (type) {
case "gl8":
return 600 * days;
case "550i":
return 500 * days;
case "bk":
return 300 * days;
}
return 0;
}
}
子类
public class Bus extends Vehicle {
private int seartCount;
public int getSeartCount() {
return seartCount;
}
public void setSeartCount(int seartCount) {
this.seartCount = seartCount;
}
public Bus() {
super();
}
public Bus(String no, int seartCount) {
super(no);
this.seartCount = seartCount;
}
public float calRent(int days) {
if (seartCount <= 16)
return 800 * days;
else
return 1500 * days;
}
}
测试类
public class Test {
public static void main(String[] args) {
Car car = new Car("11111", "bk");
System.out.println(car.calRent(10));
Bus bus = new Bus("22222", 19);
System.out.println(bus.calRent(10));
// 多态:多种形态 程序执行结果随着父类变量指向的不同而改变
// 子类对象可以直接赋值给父类变量
Vehicle vehicle = new Car("11111", "gl8");
System.out.println(vehicle.calRent(10));
Vehicle vehicle2 = new Bus("2222", 6);
System.out.println(vehicle2.calRent(10));
}
}