设计一个汽车类 Vehicle 类,包含的属性有车轮的个数 wheels 和车重 weight。小汽车类 Car 是 Vehicle 类的子类。包含的属性有载人数 loader。 卡车类 Truck 类是 Car 类的子类,其中包含的属性有载重量 payload,每 个类独有构造方法和输出相关数据的方法。java
时间: 2024-02-21 13:00:19 浏览: 101
下面是一个示例代码:
```
public class Vehicle {
private int wheels;
private double weight;
public Vehicle(int wheels, double weight) {
this.wheels = wheels;
this.weight = weight;
}
public void output() {
System.out.println("Vehicle has " + wheels + " wheels and weighs " + weight + " kg.");
}
}
public class Car extends Vehicle {
private int loader;
public Car(int wheels, double weight, int loader) {
super(wheels, weight);
this.loader = loader;
}
public void output() {
System.out.println("Car has " + wheels + " wheels, weighs " + weight + " kg, and can carry " + loader + " people.");
}
}
public class Truck extends Car {
private double payload;
public Truck(int wheels, double weight, int loader, double payload) {
super(wheels, weight, loader);
this.payload = payload;
}
public void output() {
System.out.println("Truck has " + wheels + " wheels, weighs " + weight + " kg, can carry " + loader + " people, and can carry " + payload + " kg of payload.");
}
}
```
这个代码定义了一个 Vehicle 类,一个 Car 类和一个 Truck 类,每个类都有自己的属性和构造方法。在每个类的构造方法中,使用 super 关键字调用父类的构造方法来初始化继承的属性。在每个类的 output 方法中,使用字符串拼接来输出自己的属性。