Marker Interface and Object Cloning

Marker interface is an empty interface without any fields or methods in it.

It is used to provide some special kind of instruction to JVM or Java compiler.

Examples of marker interfaces are java.lang.Cloneable, java.io.Serializable, java.rmi.Remote etc.

When we implement any empty interface, it instructs the compiler to do some special operation.

A marker interface is an empty interface with the following structure:

public interface Cloneable {
// no field or method
}

 

Object cloning with Cloneable interface

Object cloning in Java refers to the creation of exact copy of an object. It creates a new instance of the class of current object and initializes all its fields with exactly the contents of the corresponding fields of this object.

The clone() method of Object class is used to clone an object.

The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don’t implement Cloneable interface, clone() method generates CloneNotSupportedException.

The clone() method is defined in the java.lang.Object class. Syntax of the clone() method is as follows:

protected Object clone() throws CloneNotSupportedException 

 

Example of Object cloning

Let us see a simple example of object cloning using clone() method.

ObjectCloningExample.java

class Employee implements Cloneable {
int id;
String name;
String address;
double salary;

public Employee(int id, String name, String address, double salary) {
this.id = id;
this.name = name;
this.address = address;
this.salary = salary;
}

@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}

@Override
public String toString() {
return "Employee{" + "id=" + id + ", name=" + name
+ ", address=" + address + ", salary=" + salary + '}';
}

}


public class ObjectCloningExample {

public static void main(String[] args) {
Employee emp1 = new Employee(101, "Rohit Sharma", "New Delhi", 97825.95);
Employee emp2 = null;
System.out.println(emp1);

// Object cloning
try {
emp2 = (Employee) emp1.clone();
}
catch (CloneNotSupportedException ex) {
System.out.println(ex);;
}

System.out.println(emp2);
}
}

 

Output:

Employee{id=101, name=Rohit Sharma, address=New Delhi, salary=97825.95}
Employee{id=101, name=Rohit Sharma, address=New Delhi, salary=97825.95}

 

NOTE: In the above example, emp1.clone() returns an exact copy of the object emp1 and stores in the object reference emp2 using explicit casting. Remember that emp1 and emp2 have different memory locations in the JVM.

 

Important points to note in the above coding example:
1) Our class “Employee” implements Cloneable interface.
2) The class “Employee” overrides clone() method of Object class.
3) During clone() method call we handle CloneNotSupportedException using try-catch blocks.