编程定义一个汽车类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对象的信息。测试结果如下: 代码如下: CarDemo类
import java.util.GregorianCalendar;
public class CarDemo {
public static void main(String[] args) {
Car car1=new Car();
System.out.println(car1);
System.out.println("------------------");
Car car2=new Car("奥迪", "黑色", 38, new GregorianCalendar(2022,7,8));
System.out.println(car2);
}
}
Car类:
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class Car {
private String name;
private String sex;
private double price;
private Calendar date;
public Car() {
this("奥拓","土豪金",3.8,new GregorianCalendar());
}
public Car(String name, String sex, double price, Calendar date) {
super();
this.name = name;
this.sex = sex;
this.price = price;
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Calendar getDate() {
return date;
}
public void setDate(Calendar date) {
this.date = date;
}
@Override
public String toString() {
return "品牌:" + name + "\n颜色:" + sex + "\n价格:" + price + "万\n销售日期:"
+String.format("%tY年%<tm月%<td日", date) ;
}
}
|