Prototype and copying objects (brief)
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every hostel student starts from the same ShopLite cart: a bucket, a mug, an extension board and a lock. Rebuilding and re-checking it each time is slow, and sharing one cart between students is worse.
Intent: copy a configured template
A prototype is a configured object that new objects are created from by copying it and then changing the copy a little.
ShopLite's "Hostel starter kit" is a cart with a bucket, a mug, an extension board, a lock and a coupon, checked against stock once. Each student gets a copy.
Example 1 · Copying a hostel starter kit template
import java.util.ArrayList;import java.util.List;
class CartTemplate { private final String name; private final List<String> items; private String coupon;
CartTemplate(String name, List<String> items, String coupon) { this.name = name; this.items = new ArrayList<>(items); this.coupon = coupon; }
CartTemplate(CartTemplate other) { // copy constructor this.name = other.name; this.items = new ArrayList<>(other.items); // a new list, not the same one this.coupon = other.coupon; }
CartTemplate copy() { return new CartTemplate(this); }
void add(String item) { items.add(item); }
void setCoupon(String coupon) { this.coupon = coupon; }
@Override public String toString() { return name + " " + items + (coupon == null ? "" : " coupon " + coupon); }}
public class PrototypeDemo { public static void main(String[] args) { // Configured once: imagine this was loaded and checked against stock CartTemplate hostelKit = new CartTemplate("Hostel starter kit", List.of("Bucket", "Mug", "Extension board", "Lock"), "HOSTEL10");
CartTemplate asha = hostelKit.copy(); asha.add("Study lamp"); CartTemplate ravi = hostelKit.copy(); ravi.setCoupon(null);
System.out.println("Template: " + hostelKit); System.out.println("Asha: " + asha); System.out.println("Ravi: " + ravi); }}Template: Hostel starter kit [Bucket, Mug, Extension board, Lock] coupon HOSTEL10 Asha: Hostel starter kit [Bucket, Mug, Extension board, Lock, Study lamp] coupon HOSTEL10 Ravi: Hostel starter kit [Bucket, Mug, Extension board, Lock]
What this code does
- Each customer starts from
hostelKit.copy()and changes only what is different; the template itself never changes. - The copy constructor builds a new
ArrayListfrom the other list, which is why Asha's study lamp does not appear in the template or in Ravi's cart.
Every student changes only their own copy, such as adding a study lamp or dropping the coupon, so the template and everyone else's cart stay as they were.
Copy constructors are the preferred way
A copy constructor is a constructor that takes another object of the same class and copies its fields, such as Product(Product other).
A copy constructor takes an object of the same class and copies its fields. The code below compares it with clone() for copying a product.
Example 2 · Copy constructor versus clone()
import java.util.ArrayList;import java.util.List;
class Product { private final String name; private double price; private final List<String> tags;
Product(String name, double price, List<String> tags) { this.name = name; this.price = price; this.tags = new ArrayList<>(tags); }
Product(Product other) { // copy constructor reuses the main one, this(other.name, other.price, other.tags); // which already copies the list }
void setPrice(double price) { this.price = price; }
void tag(String tag) { tags.add(tag); }
@Override public String toString() { return String.format("%s Rs %.2f %s", name, price, tags); }}
class ClonedProduct implements Cloneable { String name; double price; List<String> tags = new ArrayList<>();
@Override public ClonedProduct clone() { try { return (ClonedProduct) super.clone(); // copies each field: the list is shared } catch (CloneNotSupportedException e) { throw new AssertionError(e); } }}
public class CopyConstructorDemo { public static void main(String[] args) { Product earbuds = new Product("Earbuds", 1499, List.of("audio")); Product saleCopy = new Product(earbuds); saleCopy.setPrice(1299); saleCopy.tag("sale"); System.out.println(earbuds); System.out.println(saleCopy);
ClonedProduct hoodie = new ClonedProduct(); hoodie.name = "Hoodie"; hoodie.price = 899; hoodie.tags.add("winter"); ClonedProduct copy = hoodie.clone(); copy.tags.add("sale"); System.out.println("clone() shares the list: " + hoodie.tags); }}Earbuds Rs 1499.00 [audio] Earbuds Rs 1299.00 [audio, sale] clone() shares the list: [winter, sale]
What this code does
Product(Product other)reuses the main constructor, which already copies the tag list, so the sale copy has its own price and tags.super.clone()copied the reference to the tags list, so addingsaleto the clone changed the original hoodie too. It also needed a cast and atry/catch.
For Prototype the copy constructor is the usual choice. clone() looks made for it, but you must implement Cloneable, catch a checked CloneNotSupportedException, cast the result, and super.clone() copies fields one by one, so lists are shared. A copy constructor is plain Java, works with final fields and lets you decide exactly what to copy.
Common mistake: this.tags = other.tags; in the copy constructor. It copies the reference, not the list, so the copy and the original share it.
Find the bug
Spot the copy bug
Each snippet has one wrong line. Tap it, then check the fix.
The copy must have its own tag list.
Round 1 of 2A registry of prototypes
A prototype registry is a map of named prototypes that returns a copy of the right one on request.
A registry stores named prototypes and hands out copies, so registry.create("exam") returns a fresh Exam kit every time. New templates arrive as data, not as new classes.
Example 3 · A registry of cart templates
import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Set;
class CartTemplate { private final String name; private final List<String> items;
CartTemplate(String name, List<String> items) { this.name = name; this.items = new ArrayList<>(items); }
CartTemplate(CartTemplate other) { this(other.name, other.items); }
void add(String item) { items.add(item); }
@Override public String toString() { return name + " " + items; }}
class TemplateRegistry { private final Map<String, CartTemplate> templates = new LinkedHashMap<>();
void register(String key, CartTemplate template) { templates.put(key, new CartTemplate(template)); // keep our own copy }
CartTemplate create(String key) { CartTemplate prototype = templates.get(key); if (prototype == null) throw new IllegalArgumentException("No template " + key); return new CartTemplate(prototype); // hand out a fresh copy }
Set<String> keys() { return templates.keySet(); }}
public class TemplateRegistryDemo { public static void main(String[] args) { TemplateRegistry registry = new TemplateRegistry(); registry.register("hostel", new CartTemplate("Hostel starter kit", List.of("Bucket", "Mug", "Lock"))); registry.register("exam", new CartTemplate("Exam kit", List.of("Pens x10", "Scale", "Calculator"))); registry.register("fest", new CartTemplate("College fest kit", List.of("Torch", "Power bank"))); System.out.println("Templates: " + registry.keys());
CartTemplate first = registry.create("exam"); first.add("Highlighter"); CartTemplate second = registry.create("exam"); System.out.println(first); System.out.println(second);
try { registry.create("wedding"); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } }}Templates: [hostel, exam, fest] Exam kit [Pens x10, Scale, Calculator, Highlighter] Exam kit [Pens x10, Scale, Calculator] No template wedding
What this code does
- The first customer added a highlighter to their copy; the second
create("exam")still returns the original three items. - Adding a new kit is one
registercall with data, not a new class, which is the main reason to use a registry of prototypes.
Two copies protect the registry. register stores its own copy, so the caller cannot change the template later through its old reference. create returns a copy, so a customer's changes never reach the stored prototype.
Order of execution
How a customer gets a kit
Put the steps in the order they happen.
The shallow-copy bug: shared mutable lists
A shallow copy copies the fields of an object but not the objects they point to, so the original and the copy share the same list. A deep copy also copies those mutable objects.
A shallow copy shares the lists inside; a deep copy has its own. The program below copies the same template both ways.
Example 4 · The shallow-copy bug and its fix
import java.util.ArrayList;import java.util.List;
class CartTemplate { final String name; final List<String> items;
CartTemplate(String name, List<String> items) { this.name = name; this.items = items; }
CartTemplate shallowCopy() { return new CartTemplate(name, items); // bug: same list object }
CartTemplate deepCopy() { return new CartTemplate(name, new ArrayList<>(items)); // fix: a new list }}
public class ShallowCopyBugDemo { public static void main(String[] args) { CartTemplate template = new CartTemplate("Hostel kit", new ArrayList<>(List.of("Bucket", "Mug"))); CartTemplate asha = template.shallowCopy(); asha.items.add("Lamp"); System.out.println("After Asha's shallow copy, template: " + template.items);
CartTemplate fresh = new CartTemplate("Hostel kit", new ArrayList<>(List.of("Bucket", "Mug"))); CartTemplate ravi = fresh.deepCopy(); ravi.items.add("Lamp"); System.out.println("After Ravi's deep copy, template: " + fresh.items); System.out.println("Ravi's cart: " + ravi.items); }}After Asha's shallow copy, template: [Bucket, Mug, Lamp] After Ravi's deep copy, template: [Bucket, Mug] Ravi's cart: [Bucket, Mug, Lamp]
What this code does
shallowCopypassed the same list to the new object, so Asha's lamp landed in the template that every later customer copies.deepCopymakes a newArrayList, so Ravi's changes stay in Ravi's cart.
With a shallow copy, adding a lamp to Asha's cart adds it to the template, and so to every later student's cart. The fix is a new list in the copy: new ArrayList<>(other.items).
If the list holds mutable objects, such as line items with a changeable quantity, copy each item too. Immutable items, such as String or records of strings, can be shared safely.
Predict the output
Is a new list enough?
Read the code and pick the output.
The list is new, but what about its items?
Next step
Check your understanding
9 quick questions