利用继承的思想,定义交通工具抽象类,实现汽车、火车、飞机子类,编写上转型程序并输出各个交通工具的乘坐信息。java
时间: 2024-10-16 12:17:01 浏览: 49
在Java中,利用继承的概念可以创建一个表示交通工具的抽象类`Vehicle`,然后为具体的交通工具如`Car`, `Train`, 和 `Airplane` 定义子类。这里是一个简单的示例:
```java
// 抽象车辆类
public abstract class Vehicle {
private String name;
// 构造函数
public Vehicle(String name) {
this.name = name;
}
// 抽象方法,定义乘坐信息的通用行为
public abstract void ride();
// 上转型,获取子类实例并调用抽象方法
public void showRideInfo() {
System.out.println("This is a " + name + ", and its ride information will be displayed by the subclass.");
ride(); // 调用子类的具体实现
}
}
// 子类实现
class Car extends Vehicle {
@Override
public void ride() {
System.out.println(name + " can drive on roads.");
}
}
class Train extends Vehicle {
@Override
public void ride() {
System.out.println(name + " can travel on tracks.");
}
}
class Airplane extends Vehicle {
@Override
public void ride() {
System.out.println(name + " can fly in the sky.");
}
}
// 主程序
public class Main {
public static void main(String[] args) {
Vehicle car = new Car("Car");
Vehicle train = new Train("Train");
Vehicle airplane = new Airplane("Airplane");
car.showRideInfo();
train.showRideInfo();
airplane.showRideInfo();
}
}
```
当你运行这个程序时,会分别打印出每种交通工具的乘坐信息,比如"Car can drive on roads.", "Train can travel on tracks.", "Airplane can fly in the sky."。
阅读全文