用java编写以下程序,交通工具基类Vehicle包含成员变量商标brand、颜色color;成员方法run,在控制台显示“我已经开动了”;成员方法showInfo,在控制台显示车辆的商标和颜色。卡车Truck继承了Vehicle,增加了成员变量座位数seats,重写了showInfo,增加了显示座位信息,重写了run方法,在控制台显示“卡车已经开动了”。请编写Vehicle类、Truck类。
时间: 2024-03-06 21:49:36 浏览: 39
声明Vehicle基类:
```java
public class Vehicle {
protected String brand; // 商标
protected String color; // 颜色
public Vehicle(String brand, String color) {
this.brand = brand;
this.color = color;
}
public void run() {
System.out.println("我已经开动了!");
}
public void showInfo() {
System.out.println("商标:" + brand);
System.out.println("颜色:" + color);
}
}
```
声明Truck子类:
```java
public class Truck extends Vehicle {
private int seats; // 座位数
public Truck(String brand, String color, int seats) {
super(brand, color);
this.seats = seats;
}
public void run() {
System.out.println("卡车已经开动了!");
}
public void showInfo() {
super.showInfo();
System.out.println("座位数:" + seats);
}
}
```
测试类:
```java
public class Test {
public static void main(String[] args) {
Vehicle vehicle = new Vehicle("BMW", "黑色");
vehicle.showInfo();
vehicle.run();
Truck truck = new Truck("Benz", "白色", 2);
truck.showInfo();
truck.run();
}
}
```
输出结果:
```
商标:BMW
颜色:黑色
我已经开动了!
商标:Benz
颜色:白色
座位数:2
卡车已经开动了!
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)