设计一个汽车类Vehicle,包含的属性有车轮个数wheels和车重weight。小车类Car是Vehicle的子类,其中包含的属性有载人数loader。卡车类Truck是Car类的子类,其中包含的属性有载重量payload。每个类都有构造方法和输出相关数据的方法java
时间: 2024-02-21 09:59:18 浏览: 70
好的,以下是Java版的实现:
```java
public class Vehicle {
protected int wheels;
protected int weight;
public Vehicle(int wheels, int weight) {
this.wheels = wheels;
this.weight = weight;
}
public void printInfo() {
System.out.println("Vehicle: wheels=" + wheels + ", weight=" + weight);
}
}
public class Car extends Vehicle {
protected int loader;
public Car(int wheels, int weight, int loader) {
super(wheels, weight);
this.loader = loader;
}
@Override
public void printInfo() {
System.out.println("Car: wheels=" + wheels + ", weight=" + weight + ", loader=" + loader);
}
}
public class Truck extends Car {
protected int payload;
public Truck(int wheels, int weight, int loader, int payload) {
super(wheels, weight, loader);
this.payload = payload;
}
@Override
public void printInfo() {
System.out.println("Truck: wheels=" + wheels + ", weight=" + weight + ", loader=" + loader + ", payload=" + payload);
}
}
```
使用示例:
```java
Vehicle v = new Vehicle(4, 1000);
v.printInfo();
// 输出:Vehicle: wheels=4, weight=1000
Car c = new Car(4, 1200, 5);
c.printInfo();
// 输出:Car: wheels=4, weight=1200, loader=5
Truck t = new Truck(6, 5000, 2, 8000);
t.printInfo();
// 输出:Truck: wheels=6, weight=5000, loader=2, payload=8000
```