创建一个抽象类Car,它有一个抽象方法display()和两个成员变量wheelNum、seatNum,分别表示轮子数和座位数。类bus和类motorcycle继承自类Car,实现输出成员变量的display()方法。在主方法中用向上转型对象调用display()方法
时间: 2023-12-03 11:46:38 浏览: 214
设计一个Car类
代码如下:
```java
//定义抽象类Car
public abstract class Car {
protected int wheelNum; //轮子数
protected int seatNum; //座位数
public abstract void display();
}
//bus类继承自Car类
public class Bus extends Car {
public Bus(int wheelNum, int seatNum) {
this.wheelNum = wheelNum;
this.seatNum = seatNum;
}
@Override
public void display() {
System.out.println("Bus: " + "wheelNum=" + wheelNum + ", seatNum=" + seatNum);
}
}
//motorcycle类继承自Car类
public class Motorcycle extends Car {
public Motorcycle(int wheelNum, int seatNum) {
this.wheelNum = wheelNum;
this.seatNum = seatNum;
}
@Override
public void display() {
System.out.println("Motorcycle: " + "wheelNum=" + wheelNum + ", seatNum=" + seatNum);
}
}
//主方法中用向上转型对象调用display()方法
public class Main {
public static void main(String[] args) {
Car car1 = new Bus(4, 20); //向上转型为Car类型
Car car2 = new Motorcycle(2, 2); //向上转型为Car类型
car1.display(); //调用Bus类中的display()方法
car2.display(); //调用Motorcycle类中的display()方法
}
}
```
输出结果为:
```
Bus: wheelNum=4, seatNum=20
Motorcycle: wheelNum=2, seatNum=2
```
阅读全文