编程定义一个汽车类Car。要求如下: (1)定义成员变量:品牌(String brand),价格(double price),颜色(String color),销售日期(Calendar date); (2)定义无参构造方法和带参构造方法,其中无参构造方法调用带参构造方法来初始化类中的变量; (3)定义上述成员变量所对应的getXxx()/setXxx()方法;以及一个显示所有成员信息的toString()方法; (4)定义一个测试类CarDemo,使用无参构造方法创建Car对象car1,调用toString()方法显示car1对象的信息,使用带参构造方法创建Car对象car2,调用toString()方法显示car2对象的信息。测试结果如下:
时间: 2023-12-03 20:45:17 浏览: 251
以下是Car类的代码实现:
```java
import java.util.Calendar;
public class Car {
private String brand;
private double price;
private String color;
private Calendar date;
public Car() {
this("Unknown", 0.0, "Unknown", Calendar.getInstance());
}
public Car(String brand, double price, String color, Calendar date) {
this.brand = brand;
this.price = price;
this.color = color;
this.date = date;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Calendar getDate() {
return date;
}
public void setDate(Calendar date) {
this.date = date;
}
public String toString() {
return "Brand: " + brand + ", Price: " + price + ", Color: " + color + ", Date: " + date.getTime();
}
}
```
以下是CarDemo类的代码实现:
```java
public class CarDemo {
public static void main(String[] args) {
Car car1 = new Car();
System.out.println(car1.toString());
Calendar date = Calendar.getInstance();
date.set(2022, Calendar.JANUARY, 1);
Car car2 = new Car("BMW", 50000.0, "Black", date);
System.out.println(car2.toString());
}
}
```
输出结果如下:
```
Brand: Unknown, Price: 0.0, Color: Unknown, Date: Tue Oct 05 11:29:27 CST 2021
Brand: BMW, Price: 50000.0, Color: Black, Date: Sat Jan 01 00:00:00 CST 2022
```
阅读全文