java编写一个汽车类car,属性∶品牌,车长,颜色,价格,创建五个对象,捷达,宝马,劳斯莱斯,科鲁兹,迈锐宝
时间: 2024-10-18 22:10:24 浏览: 90
在Java中,我们可以创建一个名为`Car`的类来表示汽车,包含品牌、车长、颜色和价格等属性。下面是一个简单的例子:
```java
public class Car {
private String brand;
private double length;
private String color;
private double price;
// 构造函数
public Car(String brand, double length, String color, double price) {
this.brand = brand;
this.length = length;
this.color = color;
this.price = price;
}
// 获取和设置属性的方法
public String getBrand() { return brand; }
public void setBrand(String brand) { this.brand = brand; }
public double getLength() { return length; }
public void setLength(double length) { this.length = length; }
public String getColor() { return color; }
public void setColor(String color) { this.color = color; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
@Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
", length=" + length +
", color='" + color + '\'' +
", price=" + price +
'}';
}
}
// 创建并初始化五个Car对象
public class Main {
public static void main(String[] args) {
Car jetta = new Car("捷达", 4.5, "蓝色", 100000);
Car bimmer = new Car("宝马", 5.0, "白色", 600000);
Car rollsRoyce = new Car("劳斯莱斯", 7.0, "黑色", 2000000);
Car cruze = new Car("科鲁兹", 4.8, "银色", 300000);
Car malibu = new Car("迈锐宝", 5.1, "灰色", 400000);
System.out.println(jetta);
System.out.println(bimmer);
System.out.println(rollsRoyce);
System.out.println(cruze);
System.out.println(malibu);
}
}
```
在这个例子中,我们首先定义了一个`Car`类,然后在`main`方法中创建了五个不同品牌的Car对象,并设置了它们的属性。最后通过`toString()`方法打印出每个对象的信息。
阅读全文