创建一个抽象类Car,它有一个抽象方法display()和两个成员变量wheelNum、seatNum,分别表示轮子数和座位数。类bus和类motorcycle继承自类Car,实现输出成员变量的display()方法。在主方法中用向上转型对象调用display()
时间: 2023-11-27 19:49:35 浏览: 35
以下是Java语言的实现示例:
```java
// 抽象类 Car
abstract class Car {
protected int wheelNum; // 轮子数
protected int seatNum; // 座位数
// 抽象方法 display
public abstract void display();
}
// 类 Bus 继承自 Car
class Bus extends Car {
public Bus(int wheelNum, int seatNum) {
this.wheelNum = wheelNum;
this.seatNum = seatNum;
}
// 实现 display 方法
public void display() {
System.out.println("This is a bus. It has " + wheelNum + " wheels and " + seatNum + " seats.");
}
}
// 类 Motorcycle 继承自 Car
class Motorcycle extends Car {
public Motorcycle(int wheelNum, int seatNum) {
this.wheelNum = wheelNum;
this.seatNum = seatNum;
}
// 实现 display 方法
public void display() {
System.out.println("This is a motorcycle. It has " + wheelNum + " wheels and " + seatNum + " seats.");
}
}
// 主方法
public class Main {
public static void main(String[] args) {
Car bus = new Bus(4, 50); // 向上转型为 Car 类型
Car motorcycle = new Motorcycle(2, 2);
bus.display(); // 调用 display 方法
motorcycle.display();
}
}
```
输出结果为:
```
This is a bus. It has 4 wheels and 50 seats.
This is a motorcycle. It has 2 wheels and 2 seats.
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)