在Java中编写一个商品类Product,定义属性描述商品的编号(String)、名称(String)、单价(float)、数量(int)等信息,定义4个参数的构造方法用于对商品对象的4个属性进行初始化,定义一个方法printProduct(),用于输出商品对象的四个属性值并计算商品总价值。编写一个测试类,使用泛型创建一个元素类型为Product对象的ArrayList集合,在集合对象中添加4个商品对象。遍历集合,调用每个元素的printProduct()方法,并计算输出商品的总价值。
时间: 2024-03-05 09:53:54 浏览: 25
好的,我理解了您的问题。下面是Java的代码实现:
Product.java
```java
public class Product {
private String id;
private String name;
private float price;
private int quantity;
public Product(String id, String name, float price, int quantity) {
this.id = id;
this.name = name;
this.price = price;
this.quantity = quantity;
}
public void printProduct() {
float totalPrice = price * quantity;
System.out.println("id: " + id + ", name: " + name + ", price: " + price + ", quantity: " + quantity + ", total price: " + totalPrice);
}
public float getTotalPrice() {
return price * quantity;
}
}
```
Test.java
```java
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Product> products = new ArrayList<>();
products.add(new Product("001", "Product A", 10.5f, 2));
products.add(new Product("002", "Product B", 20.0f, 3));
products.add(new Product("003", "Product C", 5.5f, 5));
products.add(new Product("004", "Product D", 15.0f, 1));
float total = 0.0f;
for (Product product : products) {
product.printProduct();
total += product.getTotalPrice();
}
System.out.println("Total price: " + total);
}
}
```
在测试类中,我们首先创建了一个元素类型为`Product`对象的`ArrayList`集合,并向其中添加四个商品对象。然后,我们遍历集合中的每个元素,调用其`printProduct()`方法,输出商品的详细信息并计算商品的总价值。最后,输出商品的总价值。
希望对您有所帮助!