Java example for Cloneable interface

//  Simple example which I found for cloneable and improve just to practise Java 😀

// If you have some notes on my implementation I will be happy to hear them.

package cloneable;

// Refered object from class for cloning

class Department implements Cloneable {

public Department(String departmentName){
this.departmentName = departmentName;
}

protected Object clone() throws CloneNotSupportedException {
Department dep = new Department(this.departmentName);
return dep;
}

private String departmentName;
}

public class CloneExp implements Cloneable {

/**
* @param args
*/
public static void main(String[] args) {
CloneExp ce = new CloneExp(“Paco”, 33, new Department(“IT”));

try{
CloneExp cloned = (CloneExp)ce.clone();
}catch (CloneNotSupportedException e) {
e.printStackTrace();
}

}

public CloneExp(String aName, int aAge, Department aDepart){
this.name = aName;
this.age = aAge;
this.depart = aDepart;

}

protected Object clone() throws CloneNotSupportedException {
CloneExp clone = (CloneExp)super.clone();
clone.depart = (Department)depart.clone();

return clone;
}

private String name;
private String address;
private int age;
private Department depart;

}

Leave a Comment

Your email address will not be published. Required fields are marked *