根据类的封装原则设计一个商品类,商品包括商品名称,商品价格,商品编号以及商品描述信息等。 要求: 至少定义两个构造方法。 价格不能为负数,如果价格为负数,默认为9999。 创建商品数组存储n个商品并进行查看。
时间: 2024-05-03 22:20:52 浏览: 10
```java
public class Commodity {
private String name;
private double price;
private int id;
private String description;
public Commodity() {
this.price = 9999;
}
public Commodity(String name, double price, int id, String description) {
this.name = name;
if (price < 0) {
this.price = 9999;
} else {
this.price = price;
}
this.id = id;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
if (price < 0) {
this.price = 9999;
} else {
this.price = price;
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
public class Main {
public static void main(String[] args) {
int n = 3;
Commodity[] commodities = new Commodity[n];
commodities[0] = new Commodity("iPhone", 9999, 1001, "Apple iPhone");
commodities[1] = new Commodity("Samsung", -3999, 1002, "Samsung Galaxy");
commodities[2] = new Commodity("Huawei", 5999, 1003, "Huawei Mate");
for (int i = 0; i < n; i++) {
System.out.println("Name: " + commodities[i].getName());
System.out.println("Price: " + commodities[i].getPrice());
System.out.println("ID: " + commodities[i].getId());
System.out.println("Description: " + commodities[i].getDescription());
}
}
}
```
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)