创建一个车辆(Vehicle)类,数据成员有:weight(重量)、type(型号),方法成员有:行驶Run()、显示车辆信息ShowVehicleInfo(),还需要编写两个构造方法,一个为无参数的构造方法;另一个为带两个参数的构造方法,两个参数分别用来初始化车辆对象的型号和重量。要求在主方法中分别用两个构造方法初始化车辆类的两个实例,并分别调用方法成员。使用java语句
时间: 2023-05-24 16:01:57 浏览: 93
java代码-请定义一个交通工具(Vehicle)的类,其中有: 属性:速度(speed),体积(size)等等 方 法: 移 动(move()) , 设置 速 度(setSpeed(int speed)) , 加速 speedUp(), 减速 speedDown()等等. 最后在测试类 Vehicle 中的 main()中实例化一个交通工具对象,并通过方法给它初始化 speed,size 的值,并且通过打印出来。另外,调用加速,减速的方法对速度进行改变。
来完成这个任务:
```java
public class Vehicle {
private double weight;
private String type;
public Vehicle() {}
public Vehicle(double weight, String type) {
this.weight = weight;
this.type = type;
}
public void Run() {
System.out.println("The vehicle is running.");
}
public void ShowVehicleInfo() {
System.out.println("The vehicle is a " + type + " and its weight is " + weight + ".");
}
}
public class Main {
public static void main(String[] args) {
Vehicle vehicle1 = new Vehicle();
Vehicle vehicle2 = new Vehicle(5000, "SUV");
vehicle1.Run();
vehicle1.ShowVehicleInfo();
vehicle2.Run();
vehicle2.ShowVehicleInfo();
}
}
```
输出结果如下:
```
The vehicle is running.
The vehicle is a null and its weight is 0.0.
The vehicle is running.
The vehicle is a SUV and its weight is 5000.0.
```
阅读全文