用java 编写商品类,包含属性 名称,类型,价格,产地。 1.为所有属性添加getter 与 setter,要求setter方法中参数名必须与属性名相同,使用this关键字 2.编写构造函数给成员属性赋值,同样需要参数名与属性名相同,使用this关键字 3.编写无参数的构造函数,要求在该构造函数中调用之前写的有参数的构造函数,使用this关键字 4.添加toStirng方法 5.测试类中使用上述多个构造方法创建对象,并显示toString()的结果
时间: 2024-02-12 07:04:35 浏览: 88
好的,下面是Java代码实现:
```java
public class Commodity {
private String name;
private String type;
private double price;
private String origin;
public Commodity(String name, String type, double price, String origin) {
this.name = name;
this.type = type;
this.price = price;
this.origin = origin;
}
public Commodity() {
this("defaultName", "defaultType", 0.0, "defaultOrigin");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
@Override
public String toString() {
return "Commodity{" +
"name='" + name + '\'' +
", type='" + type + '\'' +
", price=" + price +
", origin='" + origin + '\'' +
'}';
}
}
```
测试类的代码如下:
```java
public class CommodityTest {
public static void main(String[] args) {
Commodity c1 = new Commodity("iPhone", "Electronic", 8999.0, "China");
System.out.println(c1.toString());
Commodity c2 = new Commodity();
c2.setName("Book");
c2.setType("Stationery");
c2.setPrice(29.9);
c2.setOrigin("USA");
System.out.println(c2.toString());
}
}
```
输出结果为:
```
Commodity{name='iPhone', type='Electronic', price=8999.0, origin='China'}
Commodity{name='Book', type='Stationery', price=29.9, origin='USA'}
```
阅读全文