分别创建三个类“轮船”“汽车”和“火车
时间: 2024-11-28 18:14:24 浏览: 16
在面向对象编程中,我们可以创建三个相关的类来表示"轮船"、"汽车"和"火车",每个类都会包含它们特有的属性和行为。这里是一个简单的示例,以Java为例:
```java
// 定义一个交通工具的父类 Vehicle
public class Vehicle {
protected String name;
private int speed;
// 构造函数
public Vehicle(String name, int speed) {
this.name = name;
this.speed = speed;
}
// 简单的getters和setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getSpeed() { return speed; }
public void setSpeed(int speed) { this.speed = speed; }
// 抽象的行为,如行驶
public abstract void travel();
}
// 子类轮船 - 轮船继承Vehicle类
public class Ship extends Vehicle {
public Ship(String name, int speed) {
super(name, speed);
}
@Override
public void travel() {
System.out.println(getName() + "正在海上航行,速度:" + getSpeed());
}
}
// 子类汽车
public class Car extends Vehicle {
public Car(String name, int speed) {
super(name, speed);
}
@Override
public void travel() {
System.out.println(getName() + "正在公路上行驶,速度:" + getSpeed());
}
}
// 子类火车
public class Train extends Vehicle {
public Train(String name, int speed) {
super(name, speed);
}
@Override
public void travel() {
System.out.println(getName() + "正在铁轨上飞驰,速度:" + getSpeed());
}
}
```
阅读全文