如何通过继承在java编程中创建一个交通工具抽象类,然后分别实例化为汽车、火车和飞机子类,并演示上转型过程,最后展示每个交通工具的乘坐信息?
时间: 2024-10-20 19:14:03 浏览: 29
在Java中,我们可以创建一个`Transportation`抽象类作为交通工具的基础,包含一些通用属性和方法,如`name`、`maxSpeed`等。然后为具体的交通工具如`Car`、`Train`和`Airplane`分别创建子类,实现这些抽象方法。
```java
// 抽象类 Transportation
abstract class Transportation {
protected String name;
private int maxSpeed;
public Transportation(String name, int maxSpeed) {
this.name = name;
this.maxSpeed = maxSpeed;
}
// 公共方法
abstract void displayInfo();
public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
// 上转型示例
public static Transportation createVehicle(String vehicleType, String name, int maxSpeed) {
switch (vehicleType) {
case "Car":
return new Car(name, maxSpeed);
case "Train":
return new Train(name, maxSpeed);
case "Airplane":
return new Airplane(name, maxSpeed);
default:
throw new IllegalArgumentException("Invalid vehicle type");
}
}
// 重写displayInfo方法以显示交通工具信息
protected abstract void displayConcreteInfo();
}
class Car extends Transportation {
@Override
protected void displayConcreteInfo() {
System.out.println(name + " is a car with a max speed of " + maxSpeed + " km/h.");
}
}
class Train extends Transportation {
@Override
protected void displayConcreteInfo() {
System.out.println(name + " is a train with a max speed of " + maxSpeed + " km/h.");
}
}
class Airplane extends Transportation {
@Override
protected void displayConcreteInfo() {
System.out.println(name + " is an airplane with a max speed of " + maxSpeed + " km/h.");
}
}
public class Main {
public static void main(String[] args) {
// 创建交通工具实例并展示乘坐信息
Transportation car = Transportation.createVehicle("Car", "Toyota", 200);
car.displayInfo(); // 输出:Toyota is a car with a max speed of 200 km/h.
Transportation train = Transportation.createVehicle("Train", "Bullet Train", 300);
train.displayInfo(); // 输出:Bullet Train is a train with a max speed of 300 km/h.
Transportation airplane = Transportation.createVehicle("Airplane", "Boeing 747", 900);
airplane.displayInfo(); // 输出:Boeing 747 is an airplane with a max speed of 900 km/h.
}
}
```
在这个例子中,我们展示了如何通过继承`Transportation`抽象类创建具体的交通工具,并使用上转型技术统一处理它们。当我们调用`Transportation`类型的实例的`displayInfo()`方法时,实际上会执行子类的`displayConcreteInfo()`方法,实现了多态性。
阅读全文