(1)设计一个交通工具类,包含属性:品牌、颜色、最高时速,包含方法:驾驶、显示基本信息。 (2)设计3个子类:汽车、飞机、轮船。 (3)在测试类中,分别调用3个子类的驾驶的方法、显示基本信息的方法。
时间: 2024-05-22 07:12:10 浏览: 147
1. 交通工具类:
public class Vehicle {
private String brand;
private String color;
private int maxSpeed;
public Vehicle(String brand, String color, int maxSpeed) {
this.brand = brand;
this.color = color;
this.maxSpeed = maxSpeed;
}
public void drive() {
System.out.println("正在驾驶" + brand);
}
public void displayInfo() {
System.out.println("品牌:" + brand);
System.out.println("颜色:" + color);
System.out.println("最高时速:" + maxSpeed + "km/h");
}
}
2. 汽车类:
public class Car extends Vehicle {
public Car(String brand, String color, int maxSpeed) {
super(brand, color, maxSpeed);
}
}
3. 飞机类:
public class Airplane extends Vehicle {
public Airplane(String brand, String color, int maxSpeed) {
super(brand, color, maxSpeed);
}
}
4. 轮船类:
public class Ship extends Vehicle {
public Ship(String brand, String color, int maxSpeed) {
super(brand, color, maxSpeed);
}
}
5. 测试类:
public class Test {
public static void main(String[] args) {
Car car = new Car("奔驰", "黑色", 200);
Airplane airplane = new Airplane("波音747", "白色", 800);
Ship ship = new Ship("皇家加勒比", "蓝色", 50);
car.drive();
car.displayInfo();
airplane.drive();
airplane.displayInfo();
ship.drive();
ship.displayInfo();
}
}
输出结果:
正在驾驶奔驰
品牌:奔驰
颜色:黑色
最高时速:200km/h
正在驾驶波音747
品牌:波音747
颜色:白色
最高时速:800km/h
正在驾驶皇家加勒比
品牌:皇家加勒比
颜色:蓝色
最高时速:50km/h
阅读全文