What is the Composite pattern?
Why Interviewers Ask This
Senior OOP Concepts engineers are expected to reason about architecture, performance, and edge cases. This question separates mid-level from senior candidates by testing deep system-level understanding.
Answer
The Composite pattern composes objects into tree structures to represent part-whole hierarchies. Clients treat individual objects and compositions of objects uniformly — through the same interface. File system example: interface FileSystemComponent { String getName(); long getSize(); void display(String indent); } class File implements FileSystemComponent { private String name; private long size; public File(String name, long size) { this.name = name; this.size = size; } @Override public String getName() { return name; } @Override public long getSize() { return size; } @Override public void display(String indent) { System.out.println(indent + name + " (" + size + " bytes)"); } } class Directory implements FileSystemComponent { private String name; private List<FileSystemComponent> children = new ArrayList<>(); public Directory(String name) { this.name = name; } public void add(FileSystemComponent component) { children.add(component); } public void remove(FileSystemComponent component) { children.remove(component); } @Override public String getName() { return name; } @Override public long getSize() { return children.stream().mapToLong(FileSystemComponent::getSize).sum(); } @Override public void display(String indent) { System.out.println(indent + name + "/"); for (FileSystemComponent child : children) { child.display(indent + " "); } } } // Usage: Directory root = new Directory("root"); root.add(new File("readme.txt", 1024)); Directory src = new Directory("src"); src.add(new File("Main.java", 2048)); src.add(new File("Utils.java", 1024)); root.add(src); root.display(""); root.getSize(); // Recursive total // Client treats File and Directory uniformly!. Real uses: UI component trees (HTML DOM), menus with sub-menus, org charts, expression trees, XML/JSON parsing.
Common Mistake
Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real OOP Concepts project.
Previous
What is cohesion vs coupling trade-offs in practice?
Next
What is the Chain of Responsibility pattern?