定义机动车接口(Automobile)和非机动车接口(Nonautomobile),分别包含表示其运动模式的抽象方法;编写总的“车”类(VehicleClass),其中描述车名、车轮数,以及机动车和非机动车变量,该类实现机动车和非机动车接口;编写继承“车”类的公共汽车类(BusClass)和自行车类(BicycleClass),用main方法实现
时间: 2024-01-17 08:05:52 浏览: 118
好的,我来为您解答这个问题。
首先,我们需要定义机动车接口 `Automobile` 和非机动车接口 `Nonautomobile`,并在它们中分别包含表示其运动模式的抽象方法。代码如下:
```java
interface Automobile {
void drive();
}
interface Nonautomobile {
void pedal();
}
```
接下来,我们需要编写总的“车”类 `VehicleClass`,它描述车名、车轮数,以及机动车和非机动车变量,并且实现机动车和非机动车接口。代码如下:
```java
abstract class VehicleClass implements Automobile, Nonautomobile {
private String name;
private int wheels;
public VehicleClass(String name, int wheels) {
this.name = name;
this.wheels = wheels;
}
public String getName() {
return name;
}
public int getWheels() {
return wheels;
}
}
```
接着,我们编写继承“车”类的公共汽车类 `BusClass` 和自行车类 `BicycleClass`,并分别实现它们的运动模式。代码如下:
```java
class BusClass extends VehicleClass {
public BusClass(String name, int wheels) {
super(name, wheels);
}
@Override
public void drive() {
System.out.println("The " + getName() + " is driving.");
}
@Override
public void pedal() {
System.out.println("The " + getName() + " cannot be pedaled.");
}
}
class BicycleClass extends VehicleClass {
public BicycleClass(String name, int wheels) {
super(name, wheels);
}
@Override
public void drive() {
System.out.println("The " + getName() + " cannot be driven.");
}
@Override
public void pedal() {
System.out.println("The " + getName() + " is being pedaled.");
}
}
```
最后,我们可以在 `main` 方法中创建这些类的实例,并调用它们的方法来测试它们的功能。代码如下:
```java
public class Main {
public static void main(String[] args) {
BusClass bus = new BusClass("Bus", 4);
BicycleClass bicycle = new BicycleClass("Bicycle", 2);
System.out.println(bus.getName() + " has " + bus.getWheels() + " wheels.");
bus.drive();
bus.pedal();
System.out.println(bicycle.getName() + " has " + bicycle.getWheels() + " wheels.");
bicycle.drive();
bicycle.pedal();
}
}
```
输出结果如下:
```
Bus has 4 wheels.
The Bus is driving.
The Bus cannot be pedaled.
Bicycle has 2 wheels.
The Bicycle cannot be driven.
The Bicycle is being pedaled.
```
希望我的回答能够帮助到您!
阅读全文