建一个抽象类Car,它有wheelNum和seatNum两个成员变量以及抽象方法display()。类Bus和Motorcycle继承自Car,实现输出成员变量的display()方法。在主方法中,用向上转型对象调用display()方法。
时间: 2024-02-03 10:15:49 浏览: 163
以下是Java代码实现:
```java
//抽象类 Car
abstract class Car {
protected int wheelNum;
protected int seatNum;
public abstract void display();
}
//类 Bus
class Bus extends Car {
public Bus(int wheelNum, int seatNum) {
this.wheelNum = wheelNum;
this.seatNum = seatNum;
}
@Override
public void display() {
System.out.println("This is a bus with " + wheelNum + " wheels and " + seatNum + " seats.");
}
}
//类 Motorcycle
class Motorcycle extends Car {
public Motorcycle(int wheelNum, int seatNum) {
this.wheelNum = wheelNum;
this.seatNum = seatNum;
}
@Override
public void display() {
System.out.println("This is a motorcycle with " + wheelNum + " wheels and " + seatNum + " seat.");
}
}
//主方法
public class Main {
public static void main(String[] args) {
Car car1 = new Bus(4, 40);
Car car2 = new Motorcycle(2, 1);
car1.display(); //输出:This is a bus with 4 wheels and 40 seats.
car2.display(); //输出:This is a motorcycle with 2 wheels and 1 seat.
}
}
```
在主方法中,分别用向上转型对象car1和car2调用display()方法,输出结果是Bus类和Motorcycle类中实现的内容。
阅读全文