What is the State pattern?
Why Interviewers Ask This
Advanced questions like this reveal whether a candidate has internalized OOP Concepts deeply enough to make architectural decisions. Strong answers demonstrate both breadth and depth of experience.
Answer
The State pattern allows an object to alter its behavior when its internal state changes. The object appears to change its class. Instead of large switch/if-else based on state, each state is its own class. Vending machine example: interface VendingMachineState { void insertCoin(VendingMachine machine); void selectProduct(VendingMachine machine, String product); void dispense(VendingMachine machine); } class IdleState implements VendingMachineState { public void insertCoin(VendingMachine machine) { machine.setBalance(machine.getBalance() + 1); System.out.println("Coin accepted. Balance: $" + machine.getBalance()); machine.setState(new CoinInsertedState()); } public void selectProduct(VendingMachine machine, String product) { System.out.println("Please insert a coin first."); } public void dispense(VendingMachine machine) { System.out.println("Please insert a coin first."); } } class CoinInsertedState implements VendingMachineState { public void insertCoin(VendingMachine machine) { System.out.println("Coin already inserted. Balance: $" + machine.getBalance()); } public void selectProduct(VendingMachine machine, String product) { if (machine.hasProduct(product)) { machine.setSelectedProduct(product); machine.setState(new ProductSelectedState()); System.out.println("Selected: " + product); } else { System.out.println("Product out of stock."); } } public void dispense(VendingMachine machine) { System.out.println("Please select a product first."); } } class VendingMachine { private VendingMachineState currentState = new IdleState(); private double balance = 0; private String selectedProduct; // ... state + getters/setters public void setState(VendingMachineState state) { this.currentState = state; } public void insertCoin() { currentState.insertCoin(this); } public void selectProduct(String product) { currentState.selectProduct(this, product); } }. Benefits: state-specific behavior in state classes (no large conditionals), easy to add new states, cleaner code. Real uses: traffic lights, UI (enabled/disabled/loading), order status, network connections, game characters.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a OOP Concepts codebase.
Previous
What is the Chain of Responsibility pattern?
Next
What is meta-programming and reflection in OOP?