用Java创建一个车辆(Vehicle)类,数据成员有:weight(重量)、type(型号),方法成员有:行驶Run()、显示车辆信息ShowVehicleInfo(),还需要编写两个构造方法,一个为无参数的构造方法;另一个为带两个参数的构造方法,两个参数分别用来初始化车辆对象的型号和重量。要求在主方法中分别用两个构造方法初始化车辆类的两个实例,并分别调用方法成员。
时间: 2023-05-22 21:04:18 浏览: 209
以下是用Java创建的车辆类的代码,其中包括两个构造方法和两个方法成员:
```java
public class Vehicle {
private int weight;
private String type;
public Vehicle() {
this.type = "unknown";
this.weight = 0;
}
public Vehicle(String type, int weight) {
this.type = type;
this.weight = weight;
}
public void Run() {
System.out.println("The vehicle is running.");
}
public void ShowVehicleInfo() {
System.out.println("Vehicle type: " + this.type);
System.out.println("Vehicle weight: " + this.weight);
}
public static void main(String[] args) {
Vehicle vehicle1 = new Vehicle();
Vehicle vehicle2 = new Vehicle("SUV", 2000);
vehicle1.Run();
vehicle1.ShowVehicleInfo();
vehicle2.Run();
vehicle2.ShowVehicleInfo();
}
}
```
输出结果如下:
```
The vehicle is running.
Vehicle type: unknown
Vehicle weight: 0
The vehicle is running.
Vehicle type: SUV
Vehicle weight: 2000
```
阅读全文