The Prototype pattern in Java is implemented by having a class implement the Cloneable marker interface and override Object's clone() method to return a copy of itself, which callers use instead of constructing a new instance from scratch.
Key Points: • Implementing Cloneable signals to the JVM that Object.clone() is legally allowed on the class. • Overriding clone() lets you control exactly what gets copied, including converting a shallow copy into a deep copy where needed. • The default Object.clone() implementation performs a shallow, field-by-field copy. • For deep copies, referenced mutable fields must be cloned explicitly inside the overridden clone() method. • Alternatives to Cloneable, such as a copy constructor or a dedicated copy() factory method, are often preferred for clearer, safer cloning semantics.
Example: A Configuration object that's expensive to rebuild can implement Cloneable and override clone() to return a copy that a caller can then tweak for a specific request, instead of re-running the original, costly initialization logic.
Code Example:
class Configuration implements Cloneable {
private Map<String, String> settings;
@Override
public Configuration clone() {
try {
Configuration copy = (Configuration) super.clone();
copy.settings = new HashMap<>(this.settings); // deep copy the map
return copy;
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
}Interview Tip: A concise interview answer is:
"I implement Prototype by having the class implement Cloneable and override clone(), calling super.clone() for the shallow copy and then explicitly copying any mutable referenced fields if I need a deep copy — that way cloning an existing instance replaces expensive re-initialization from scratch."