编程定义一个汽车类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对象的信息。java代码
时间: 2023-11-28 11:48:12 浏览: 24
```
import java.util.Calendar;
public class Car {
private String brand;
private double price;
private String color;
private Calendar date;
public Car() {
this("default", 0, "white", 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;
}
@Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
", price=" + price +
", color='" + color + '\'' +
", date=" + date.getTime() +
'}';
}
}
public class CarDemo {
public static void main(String[] args) {
Car car1 = new Car();
System.out.println(car1.toString() + " Current time: " + Calendar.getInstance().getTime());
Calendar date = Calendar.getInstance();
date.set(2021, Calendar.JANUARY, 1);
Car car2 = new Car("BMW", 1000000, "black", date);
System.out.println(car2.toString());
}
}
```
阅读全文