请定义一个交通工具(Car)的类,其中有两个属性,分别是速度、车的类型,并且有四个方法,移动move()、设置速度setSpeed(double s)、加速speedUp(double f)、减速speedDOwn(double j),最后在测试类中的main()中实例化一个保时捷911对象,并通过构造方法给它初始化speed,type的值, 并且打印出来。另外,调用加速,减速的发放对速度进行改变。
时间: 2023-05-21 15:02:09 浏览: 56
好的,我可以回答这个问题。以下是定义交通工具(Car)类的代码:
```java
public class Car {
private double speed;
private String type;
public Car(double speed, String type) {
this.speed = speed;
this.type = type;
}
public void move() {
System.out.println("The car is moving.");
}
public void setSpeed(double s) {
this.speed = s;
}
public void speedUp(double f) {
this.speed += f;
}
public void speedDown(double j) {
this.speed -= j;
}
}
```
在测试类中的main()中实例化一个保时捷911对象,并通过构造方法给它初始化speed,type的值,并且打印出来,代码如下:
```java
public class TestCar {
public static void main(String[] args) {
Car porsche = new Car(200, "sports car");
System.out.println("The Porsche 911 has a speed of " + porsche.speed + " km/h and is a " + porsche.type + ".");
porsche.speedUp(50);
System.out.println("After accelerating, the speed of the Porsche 911 is " + porsche.speed + " km/h.");
porsche.speedDown(30);
System.out.println("After decelerating, the speed of the Porsche 911 is " + porsche.speed + " km/h.");
}
}
```
输出结果如下:
```
The Porsche 911 has a speed of 200.0 km/h and is a sports car.
After accelerating, the speed of the Porsche 911 is 250.0 km/h.
After decelerating, the speed of the Porsche 911 is 220.0 km/h.
```
希望这个回答能够帮到你!
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)