创建一个商品类Product类: 定义3个属性id,name,price,分别实现setter()和getter()方法; 重写toString()方法,输出所有属性内容; 创建一个测试类Demo5_12: 1.调用Product类的构造函数实例化三个对象,并保存至 一个ArrayList 集合中; 2. 最后遍历该集合,输出商品信息。
时间: 2024-03-16 09:45:24 浏览: 155
好的,我理解了你的要求。下面是Java代码实现:
Product类:
```java
public class Product {
private int id;
private String name;
private double price;
public Product(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
'}';
}
}
```
Demo5_12类:
```java
import java.util.ArrayList;
public class Demo5_12 {
public static void main(String[] args) {
ArrayList<Product> products = new ArrayList<>();
Product product1 = new Product(1, "iPhone X", 999.99);
Product product2 = new Product(2, "Samsung Galaxy S10", 899.99);
Product product3 = new Product(3, "Google Pixel 3", 799.99);
products.add(product1);
products.add(product2);
products.add(product3);
for (Product p : products) {
System.out.println(p);
}
}
}
```
输出结果:
```
Product{id=1, name='iPhone X', price=999.99}
Product{id=2, name='Samsung Galaxy S10', price=899.99}
Product{id=3, name='Google Pixel 3', price=799.99}
```
希望能帮到你!
阅读全文