java如何代表物品
在Java中,代表物品通常通过创建类(Class)来实现,类可以封装物品的属性和行为。以下是几种常见的方法:
使用类定义物品
定义一个类来表示物品的基本结构,包含属性和方法:
public class Item {
private String name;
private double price;
private int quantity;
public Item(String name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
使用记录类(Java 14+)
对于简单的不可变物品,可以使用记录类(Record)简化代码:
public record Item(String name, double price, int quantity) {}
使用枚举表示固定物品类型
如果物品类型是固定的,可以使用枚举:
public enum ItemType {
BOOK("Book", 20.0),
PEN("Pen", 5.0),
NOTEBOOK("Notebook", 15.0);
private final String name;
private final double price;
ItemType(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
使用集合管理多个物品
通过集合(如List或Map)管理多个物品实例:
List<Item> itemList = new ArrayList<>();
itemList.add(new Item("Laptop", 999.99, 1));
itemList.add(new Item("Mouse", 25.50, 2));
Map<String, Item> itemMap = new HashMap<>();
itemMap.put("item1", new Item("Keyboard", 45.00, 1));
实现物品的行为
为物品添加方法以定义其行为:

public class ElectronicItem extends Item {
private int warrantyMonths;
public ElectronicItem(String name, double price, int quantity, int warrantyMonths) {
super(name, price, quantity);
this.warrantyMonths = warrantyMonths;
}
public void extendWarranty(int months) {
this.warrantyMonths += months;
}
}





