Composite: trees of objects
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's catalogue has categories inside categories. How do you count the products under Electronics, however deep the tree goes, without writing a new loop for every level?
The problem: categories inside categories
The Composite pattern lets you treat one object and a group of objects in the same way, because both offer the same interface.
ShopLite's catalogue is a tree: Electronics holds a Power bank and an Audio category, and Audio holds Earbuds and a Wireless category. Example 1 counts its products with loops and instanceof.
Example 1 · Without composite: a two-level loop gives the wrong count
import java.util.ArrayList;import java.util.List;
class Product { final String name;
Product(String name) { this.name = name; }}
class Category { final String name; final List<Object> children = new ArrayList<>(); // products and categories mixed
Category(String name) { this.name = name; }}
public class NoCompositeDemo { static int countProducts(Category category) { int count = 0; for (Object child : category.children) { if (child instanceof Product) { count++; } else if (child instanceof Category sub) { // handles one level down only for (Object inner : sub.children) { if (inner instanceof Product) { count++; } } } } return count; }
public static void main(String[] args) { Category wireless = new Category("Wireless"); wireless.children.add(new Product("Neckband"));
Category audio = new Category("Audio"); audio.children.add(new Product("Earbuds")); audio.children.add(new Product("Headphones")); audio.children.add(wireless);
Category electronics = new Category("Electronics"); electronics.children.add(new Product("Power bank")); electronics.children.add(audio);
System.out.println("Products counted: " + countProducts(electronics) + " (real number: 4)"); }}Products counted: 3 (real number: 4)
What this code does
- The method checks types with
instanceofand has one loop per level. The Neckband sits three levels down, so it is never counted. - Adding another loop would only move the limit one level deeper. The real fix is to let each object count itself.
A tree is a structure where some boxes hold other boxes and some are just things. If categories and products are unrelated classes, every operation needs instanceof checks and one loop per level.
Code written for two levels silently gives wrong answers the day someone adds a third.
Component interface with leaf and composite classes
A composite holds a list of components, which can be leaves or other composites, and answers each method by asking its children and combining their answers.
CatalogItem is the shared interface. Product implements it as a leaf, and Category implements it as a composite that holds a list of items. Example 2 counts products at any depth.
Example 2 · CatalogItem, Product and Category: recursion counts any depth
import java.util.ArrayList;import java.util.List;
interface CatalogItem { // component String name(); int productCount();}
class Product implements CatalogItem { // leaf private final String name; private final int price;
Product(String name, int price) { this.name = name; this.price = price; }
public String name() { return name; } public int productCount() { return 1; }}
class Category implements CatalogItem { // composite private final String name; private final List<CatalogItem> children = new ArrayList<>();
Category(String name) { this.name = name; }
Category add(CatalogItem item) { children.add(item); return this; }
public String name() { return name; }
public int productCount() { int total = 0; for (CatalogItem child : children) { total += child.productCount(); } return total; }}
public class CompositeCountDemo { public static void main(String[] args) { Category wireless = new Category("Wireless").add(new Product("Neckband", 1299)); Category audio = new Category("Audio") .add(new Product("Earbuds", 1499)) .add(new Product("Headphones", 2499)) .add(wireless); Category electronics = new Category("Electronics") .add(new Product("Power bank", 999)) .add(audio);
CatalogItem[] items = {electronics, audio, new Product("Pen", 20)}; for (CatalogItem item : items) { System.out.println(item.name() + ": " + item.productCount() + " product(s)"); } }}Electronics: 4 product(s) Audio: 3 product(s) Pen: 1 product(s)
What this code does
Category.productCountasks each child for its count. A product answers 1; a category runs the same method on its own children, however deep they go.- The loop in
maintreats a whole category tree and a single pen the same way: both areCatalogItems.
Three parts take part in the pattern:
- Component: the interface both kinds share (
CatalogItem). - Leaf: an item with no children (
Product). - Composite: holds components and combines their answers (
Category).
Clients see only CatalogItem, so they never check which kind they have.
add only on the composite class (safer: product.add(...) will not compile) or on the interface too (every item looks the same, but leaves must reject it at runtime). Most Java code chooses the safer option.Recursive operations: total price of a product bundle
A recursive operation is a method that calls the same method on the children until it reaches the leaves, which answer directly.
A product bundle, such as a hostel starter kit, is a composite: its price is the sum of its parts' prices minus its own discount. Example 3 puts one bundle inside another.
Example 3 · Bundles inside bundles: a hostel starter kit
import java.util.ArrayList;import java.util.List;
interface Sellable { String name(); int price();}
class Product implements Sellable { private final String name; private final int price;
Product(String name, int price) { this.name = name; this.price = price; }
public String name() { return name; } public int price() { return price; }}
class Bundle implements Sellable { private final String name; private final int discountPercent; private final List<Sellable> parts = new ArrayList<>();
Bundle(String name, int discountPercent) { this.name = name; this.discountPercent = discountPercent; }
Bundle add(Sellable part) { parts.add(part); return this; }
public String name() { return name; }
public int price() { int sum = 0; for (Sellable part : parts) { sum += part.price(); // recursion into inner bundles } return sum - sum * discountPercent / 100; }}
public class BundlePriceDemo { public static void main(String[] args) { Bundle study = new Bundle("Study combo", 5) .add(new Product("Desk lamp", 699)) .add(new Product("Notebook pack", 240)); Bundle kit = new Bundle("Hostel starter kit", 10) .add(new Product("Bucket", 249)) .add(new Product("Mug", 199)) .add(study);
System.out.println(study.name() + ": Rs " + study.price()); System.out.println(kit.name() + ": Rs " + kit.price()); }}Study combo: Rs 893 Hostel starter kit: Rs 1207
What this code does
- The study combo costs 699 + 240 = 939, minus 5% (46 with whole-rupee maths) = 893. The kit then adds 249 + 199 + 893 = 1341 and takes 10% off: 1207.
- The kit never asks whether a part is a product or a bundle. It calls
price(), and each part works out its own answer.
The recursion stops at the leaves, which simply return their own price. A composite needs no idea how deep the tree below it goes: it asks each part and adds up the answers.
Find the bug
Find the bug in the bundle price
Each version of Bundle.price() has one wrong line. Click it.
The bundle price ignores what the parts cost.
Round 1 of 2Printing a category tree with indentation
Depth is how many levels below the top an item sits. The top item has depth 0, and printing code uses the depth to indent each line.
To print the tree, pass the depth into the method. Each item prints itself indented by its depth, and a composite then prints its children with depth + 1.
Example 4 · Printing the category tree with indentation
import java.util.ArrayList;import java.util.List;
interface CatalogItem { int productCount(); void print(int depth);}
class Product implements CatalogItem { private final String name; private final int price;
Product(String name, int price) { this.name = name; this.price = price; }
public int productCount() { return 1; }
public void print(int depth) { System.out.println(" ".repeat(depth) + "- " + name + " Rs " + price); }}
class Category implements CatalogItem { private final String name; private final List<CatalogItem> children = new ArrayList<>();
Category(String name) { this.name = name; }
Category add(CatalogItem item) { children.add(item); return this; }
public int productCount() { int total = 0; for (CatalogItem child : children) { total += child.productCount(); } return total; }
public void print(int depth) { System.out.println(" ".repeat(depth) + "+ " + name + " (" + productCount() + ")"); for (CatalogItem child : children) { child.print(depth + 1); // children one level deeper } }}
public class CategoryTreeDemo { public static void main(String[] args) { Category shop = new Category("ShopLite") .add(new Category("Electronics") .add(new Product("Power bank", 999)) .add(new Category("Audio") .add(new Product("Earbuds", 1499)) .add(new Product("Headphones", 2499)))) .add(new Category("Stationery") .add(new Product("Gel pen", 20)) .add(new Product("Notebook pack", 240))); shop.print(0); }}+ ShopLite (5)
+ Electronics (3)
- Power bank Rs 999
+ Audio (2)
- Earbuds Rs 1499
- Headphones Rs 2499
+ Stationery (2)
- Gel pen Rs 20
- Notebook pack Rs 240What this code does
- Each line is indented by two spaces per level. A category prints its own line first and then hands
depth + 1to its children. - The product count in brackets is a second recursive operation used inside the first. Both are short because each class handles only its own case.
The same idea gives you breadcrumbs, menus and "show all products under Electronics". Each operation is one method in the interface with two small implementations.
Predict the output
Which depth does each item get?
Printing starts at Electronics with depth 0. Pick the answer.
Round 1 of 2
Audio is a child of Electronics. How is it printed with two spaces per level?
Where composite appears: file systems, menus, UI trees
Example 5 shows a file system: files are leaves, folders are composites, and a folder's size is the sum of everything inside it.
Example 5 · A file system is a composite: folder sizes
import java.util.ArrayList;import java.util.List;
interface Node { long sizeKb(); void print(String indent);}
class FileNode implements Node { private final String name; private final long sizeKb;
FileNode(String name, long sizeKb) { this.name = name; this.sizeKb = sizeKb; }
public long sizeKb() { return sizeKb; }
public void print(String indent) { System.out.println(indent + name + " (" + sizeKb + " KB)"); }}
class Folder implements Node { private final String name; private final List<Node> children = new ArrayList<>();
Folder(String name) { this.name = name; }
Folder add(Node node) { children.add(node); return this; }
public long sizeKb() { long total = 0; for (Node child : children) { total += child.sizeKb(); } return total; }
public void print(String indent) { System.out.println(indent + name + "/ (" + sizeKb() + " KB)"); for (Node child : children) { child.print(indent + " "); } }}
public class FileTreeDemo { public static void main(String[] args) { Folder project = new Folder("shoplite") .add(new Folder("src") .add(new FileNode("Order.java", 3)) .add(new FileNode("Checkout.java", 5))) .add(new Folder("docs") .add(new FileNode("README.md", 2))) .add(new FileNode("build.log", 120)); project.print(""); }}shoplite/ (130 KB)
src/ (8 KB)
Order.java (3 KB)
Checkout.java (5 KB)
docs/ (2 KB)
README.md (2 KB)
build.log (120 KB)What this code does
- This is the same pattern with different names:
FileNodeis the leaf,Folderthe composite,Nodethe component. A folder's size is the sum of everything inside it. - Here the indent is passed as text instead of a depth number. Either works, as long as each level adds the same amount.
Composites are everywhere trees are. A navigation menu has items and submenus. In Java Swing, a JPanel is a component that holds other components, so a whole screen is one tree.
The HTML of a web page is also a tree of elements, and the same "ask the children and combine" idea is used to measure and draw it.
Next step
Check your understanding
12 quick questions