OOP practice: an inventory and week 6 review
Designing with objects is a skill learned by practicing. In this lesson you will build step by step a small inventory system with several classes that collaborate with each other. The key question at the start is: which things exist in my problem and what does each one know how to do? Each thing becomes a class; what the thing knows are its fields and what it can do are its methods. It is important that each class has a single responsibility: an item describes itself, the inventory manages the collection.
Enum: a fixed set of values
Before the inventory we need a new tool: the enum. An enum defines a type with a fixed number of possible values, such as product categories, days of the week or order states. It is much safer than using a String or an int, because the compiler rejects any value that is not in the list and typing errors (like "foood") disappear. An enum works wonderfully with switch, and it can have its own fields and methods, which makes it a special class with fixed instances.
public class Main {
enum Level {
LOW(1), MEDIUM(5), HIGH(10);
private final int weight;
Level(int weight) { this.weight = weight; }
int getWeight() { return weight; }
}
public static void main(String[] args) {
Level level = Level.MEDIUM;
System.out.println(level); // MEDIUM
System.out.println(level.getWeight()); // 5
System.out.println(level.ordinal()); // 1 (position in the list)
System.out.println(Level.valueOf("HIGH")); // HIGH
for (Level l : Level.values()) {
String text = switch (l) {
case LOW -> "relax";
case MEDIUM -> "pay attention";
case HIGH -> "urgent";
};
System.out.println(l + ": " + text);
}
}
}The inventory system
We have three pieces. Category is an enum with the categories. Item is a class with name, category, price and quantity; it knows how to compute its total value and sell units, and it protects itself by rejecting invalid quantities. Inventory holds a list of items and offers high-level operations: add, search by name, compute the warehouse value and list those with low stock. Notice how main never touches the internal list: it only talks to Inventory, and Inventory only talks to Item. That separation lets each part change without affecting the others.
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class Main {
public static void main(String[] args) {
Inventory inventory = new Inventory();
inventory.add(new Item("Laptop", Category.TECH, 899.99, 5));
inventory.add(new Item("Mouse", Category.TECH, 19.5, 40));
inventory.add(new Item("Apple", Category.FOOD, 0.5, 3));
System.out.printf("Total value: %.2f%n", inventory.totalValue());
Optional<Item> found = inventory.findByName("mouse");
System.out.println(found.isPresent() ? found.get() : "not found");
System.out.println(inventory.sell("Laptop", 2)); // true
System.out.println(inventory.sell("Laptop", 10)); // false: not enough stock
System.out.println("Low stock:");
for (Item item : inventory.lowStock(5)) {
System.out.println(" - " + item);
}
}
}
enum Category { TECH, FOOD, HOME }
class Item {
private final String name;
private final Category category;
private final double price;
private int quantity;
Item(String name, Category category, double price, int quantity) {
if (price < 0 || quantity < 0) throw new IllegalArgumentException("invalid data");
this.name = name;
this.category = category;
this.price = price;
this.quantity = quantity;
}
String getName() { return name; }
int getQuantity() { return quantity; }
double totalValue() { return price * quantity; }
boolean sell(int units) {
if (units <= 0 || units > quantity) return false;
quantity -= units;
return true;
}
@Override
public String toString() {
return name + " [" + category + "] x" + quantity;
}
}
class Inventory {
private final List<Item> items = new ArrayList<>();
void add(Item item) { items.add(item); }
double totalValue() {
double total = 0;
for (Item item : items) total += item.totalValue();
return total;
}
Optional<Item> findByName(String name) {
for (Item item : items) {
if (item.getName().equalsIgnoreCase(name)) return Optional.of(item);
}
return Optional.empty();
}
boolean sell(String name, int units) {
Optional<Item> item = findByName(name);
return item.isPresent() && item.get().sell(units);
}
List<Item> lowStock(int limit) {
List<Item> result = new ArrayList<>();
for (Item item : items) {
if (item.getQuantity() <= limit) result.add(item);
}
return result;
}
}Optional<Item> is a container that either holds a value or is empty; it is the modern way to say that a search may find nothing, instead of returning null and risking a NullPointerException. It is queried with isPresent() and get(), or better with methods such as orElse and ifPresent. And now, the review: week 6 gave you classes with fields, constructor and methods; objects created with new and references that can be null; encapsulation with private; equals and toString; records for immutable data and enums for fixed sets of values.
Teste dein Wissen
Frage 1 von 6What does the word private do on a field?
✎ Meine Notizen
Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen