1、利用继承的思想,定义交通工具抽象类,实现汽车、火车、飞机子类,编写 上转型程序并输出各个交通工具的乘坐信息。
时间: 2024-10-21 09:14:47 浏览: 50
首先,我们可以创建一个名为`Transportation`的抽象类,它包含一些通用的属性和方法,比如座位数和乘坐信息。然后,我们会为`Car`、`Train`和`Airplane`这三种具体的交通工具分别定义子类,并继承自`Transportation`。
```java
// Transportation抽象类
abstract class Transportation {
protected int seats;
public Transportation(int seats) {
this.seats = seats;
}
// 具体方法如获取乘坐信息
abstract String getPassengerInfo();
}
// 子类 - Car
class Car extends Transportation {
public Car(int seats) {
super(seats);
}
@Override
public String getPassengerInfo() {
return "汽车," + seats + "个座位";
}
}
// 子类 - Train
class Train extends Transportation {
public Train(int seats) {
super(seats);
}
@Override
public String getPassengerInfo() {
return "火车," + seats + "节车厢";
}
}
// 子类 - Airplane
class Airplane extends Transportation {
public Airplane(int seats) {
super(seats);
}
@Override
public String getPassengerInfo() {
return "飞机," + seats + "个座位";
}
}
public class Main {
public static void main(String[] args) {
Transportation car = new Car(50);
Transportation train = new Train(1000);
Transportation airplane = new Airplane(500);
System.out.println(car.getPassengerInfo());
System.out.println(train.getPassengerInfo());
System.out.println(airplane.getPassengerInfo());
}
}
```
在这个例子中,上转型是指我们可以在`main`函数中创建`Transportation`类型的对象,但实际上存储的是其子类的对象。运行此程序会输出各自交通工具的乘坐信息。
阅读全文