抽象类Vehicle,非抽象子类Car类,均实现接口ProhibitDrivingProhibitDriving方法:boolean prohibitDriving(enum Day)Vehicle属性:车牌号;- 实现prohibitDriving方法:比如周一限行尾号o,5:Car继承父类Vehicle- 若干构造方法(Car属性自定义), getter、setter写测试类carTest,声明对象myCar,设置车牌;声明接口变量goOut;(输入今日周几)用goOut判断是否限行
时间: 2023-12-14 13:40:09 浏览: 36
以下是Java代码实现:
```java
// 定义Vehicle抽象类
public abstract class Vehicle {
protected String licensePlate;
public Vehicle(String licensePlate) {
this.licensePlate = licensePlate;
}
public abstract boolean prohibitDriving(Day day);
public String getLicensePlate() {
return licensePlate;
}
public void setLicensePlate(String licensePlate) {
this.licensePlate = licensePlate;
}
}
// 定义Car类,继承自Vehicle类
public class Car extends Vehicle {
private String brand;
private int seats;
public Car(String licensePlate, String brand, int seats) {
super(licensePlate);
this.brand = brand;
this.seats = seats;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getSeats() {
return seats;
}
public void setSeats(int seats) {
this.seats = seats;
}
@Override
public boolean prohibitDriving(Day day) {
int lastDigit = Integer.parseInt(licensePlate.substring(licensePlate.length() - 1));
switch (day) {
case MONDAY:
return lastDigit == 0 || lastDigit == 5;
case TUESDAY:
return lastDigit == 1 || lastDigit == 6;
case WEDNESDAY:
return lastDigit == 2 || lastDigit == 7;
case THURSDAY:
return lastDigit == 3 || lastDigit == 8;
case FRIDAY:
return lastDigit == 4 || lastDigit == 9;
default:
return false;
}
}
}
// 定义Day枚举类型
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
// 定义ProhibitDriving接口
public interface ProhibitDriving {
boolean prohibitDriving(Day day);
}
// 编写测试类
public class CarTest {
public static void main(String[] args) {
Car myCar = new Car("粤B12345", "Toyota", 5);
ProhibitDriving goOut = myCar;
Day today = Day.MONDAY;
if (goOut.prohibitDriving(today)) {
System.out.println("今天是" + today + "," + myCar.getLicensePlate() + "限行!");
} else {
System.out.println("今天是" + today + "," + myCar.getLicensePlate() + "可以上路!");
}
}
}
```
在测试类中,首先创建了一个车牌号为"粤B12345",品牌为"Toyota",座位数为5的汽车对象myCar,并将其赋值给接口变量goOut。然后根据输入的日期判断是否限行,并输出相应信息。在本例中,假设今天是星期一,因此myCar的车牌号最后一位数字为5,因此该车在星期一限行,输出结果如下:
```
今天是MONDAY,粤B12345限行!
```