定义多个构造方法完成对手机类属性的赋值。 1) 创建一个类,类名为Phone。 2) 声明类的属性,包括品牌、颜色、价格。 3) 编写4个构造方法完成对3个属性的赋值。 提示:一个无参构造方法,三个有参构造方法 4) 编写方法show():功能是输出对象属性信息。 5) 在main方法中实例化2个对象,通过构造方法完成属性赋值,调用show()输出属性信息。
时间: 2023-05-31 19:06:52 浏览: 49
代码如下:
public class Phone {
private String brand;
private String color;
private double price;
// 无参构造方法
public Phone() {
this.brand = "Unknown";
this.color = "Unknown";
this.price = 0.0;
}
// 有参构造方法1
public Phone(String brand) {
this.brand = brand;
this.color = "Unknown";
this.price = 0.0;
}
// 有参构造方法2
public Phone(String brand, String color) {
this.brand = brand;
this.color = color;
this.price = 0.0;
}
// 有参构造方法3
public Phone(String brand, String color, double price) {
this.brand = brand;
this.color = color;
this.price = price;
}
// 输出对象属性信息
public void show() {
System.out.println("Brand: " + this.brand + ", Color: " + this.color + ", Price: " + this.price);
}
public static void main(String[] args) {
// 实例化对象,通过不同的构造方法完成属性赋值
Phone phone1 = new Phone();
Phone phone2 = new Phone("Apple", "White");
Phone phone3 = new Phone("Samsung", "Black", 5999.0);
// 调用show()方法输出属性信息
phone1.show();
phone2.show();
phone3.show();
}
}