Junior — Middle
What internal elements of objects do you use to implement business logic and processes?
sobes.tech AI
Answer from AI
To implement business logic and processes in objects in Java, methods and internal fields (state variables) are usually used.
- Fields store the state of the object, necessary data.
- Methods contain the logic for processing this data, implement business processes, and facilitate interaction with other objects.
For example, in the Order class, there may be fields for storing a list of products and the order status, and methods for adding a product, calculating the total cost, and changing the status:
public class Order {
private List<Item> items = new ArrayList<>();
private String status;
public void addItem(Item item) {
items.add(item);
}
public double calculateTotal() {
return items.stream().mapToDouble(Item::getPrice).sum();
}
public void setStatus(String status) {
this.status = status;
}
}
Thus, business logic is encapsulated in methods, and data is stored in object fields.