Difficulty 2

Prototype Pattern

Object that supports cloning is called a prototype.

The concept is to copy an existing object rather than creating a new instance from scratch, meaning we create object within existing object itself.

When to use:

– when need for copying existing objects without making the code dependent on their classes
– when object creation is costly

How to:

1. a cloneable object must implement an interface Cloneable, this is an indication that it’s legal to make a field-to-field copy
2. every class that implements it, must override the clone() method


– interface Cloneable is a tagging interface, meaning it has no methods and it’s used solely to provide runtime information about the object
– method clone() is defined in java.lang.Object class
– invoking clone() method on an object that doesn’t implement Cloneable will result in CloneNotSupportedException
– class that implements Cloneable should implement it’s own public clone() method (overriding Objects protected clone() method)

Example – Prototype implementation using Cloneable interface

class Color implements Cloneable {
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
return clone;

Last update 16.07.2019.
For possible mistakes in content or typos, I apologise and kindly ask you to report here.