请定义一个交通工具(Vehicle)的类,其中有: 属性:速度(speed),车的类型(type)等等 方法:移动(move()),设置速度(setSpeed(double s)),加速speedUp(double s),减速speedDown(double s)等等. 最后在测试类Vehicle中的main()中实例化一个交通工具对象, 并通过构造方法给它初始化speed,type的值,并且打印出来。另外,调用加速,减速的方法对速度进行改变。
时间: 2023-05-21 12:00:44 浏览: 137
好的,以下是交通工具(Vehicle)的类的定义:
```java
public class Vehicle {
private double speed;
private String type;
public Vehicle(double speed, String type) {
this.speed = speed;
this.type = type;
}
public void move() {
System.out.println("The vehicle is moving.");
}
public void setSpeed(double s) {
this.speed = s;
}
public void speedUp(double s) {
this.speed += s;
}
public void speedDown(double s) {
this.speed -= s;
}
public double getSpeed() {
return this.speed;
}
public String getType() {
return this.type;
}
}
```
在测试类Vehicle中的main()中实例化一个交通工具对象,并通过构造方法给它初始化speed,type的值,并且打印出来。另外,调用加速,减速的方法对速度进行改变。
```java
public class VehicleTest {
public static void main(String[] args) {
Vehicle car = new Vehicle(60, "car");
System.out.println("Type: " + car.getType() + ", Speed: " + car.getSpeed());
car.speedUp(20);
System.out.println("Type: " + car.getType() + ", Speed: " + car.getSpeed());
car.speedDown(10);
System.out.println("Type: " + car.getType() + ", Speed: " + car.getSpeed());
}
}
```
输出结果如下:
```
Type: car, Speed: 60.0
Type: car, Speed: 80.0
Type: car, Speed: 70.0
```
阅读全文