定义数组存储3个汽车对象。汽车的属性:品牌,价格,颜色。汽车的功能:前进,后退,驻车,空挡,注意各个功能中只需要输出一句话即可。创建四个汽车对象,并把汽车对象存入到数组当中。遍历数组,每一个数组中的汽车对象执行不同的功能。
时间: 2024-05-01 12:22:04 浏览: 25
以下是使用 Java 语言实现的代码:
```java
public class Car {
private String brand;
private double price;
private String color;
public Car(String brand, double price, String color) {
this.brand = brand;
this.price = price;
this.color = color;
}
public void forward() {
System.out.println(brand + " is moving forward.");
}
public void backward() {
System.out.println(brand + " is moving backward.");
}
public void park() {
System.out.println(brand + " is parked.");
}
public void neutral() {
System.out.println(brand + " is in neutral.");
}
public static void main(String[] args) {
Car[] cars = new Car[3];
cars[0] = new Car("Toyota", 20000, "Red");
cars[1] = new Car("Honda", 25000, "Silver");
cars[2] = new Car("BMW", 50000, "Black");
for (Car car : cars) {
car.forward();
car.backward();
car.park();
car.neutral();
System.out.println();
}
}
}
```
输出结果如下:
```
Toyota is moving forward.
Toyota is moving backward.
Toyota is parked.
Toyota is in neutral.
Honda is moving forward.
Honda is moving backward.
Honda is parked.
Honda is in neutral.
BMW is moving forward.
BMW is moving backward.
BMW is parked.
BMW is in neutral.
```