In this Example, you can find the Cloneable interface and Clone method usage in java. and also various ways to create object in java.
/*
* Object cloning is a way to create exact copy of an object.
* To use clone() method of java.lang.Cloneable interface, class must implement it else CloneNotSupportException will be thrown.
*/
class TestClone implements Cloneable { int a; int b; TestClone(int a,int b){ this.a = a; this.b = b; } public Object clone() throws CloneNotSupportedException { return super.clone(); } } public class CloningTest { public static void main(String a[]) throws CloneNotSupportedException { TestClone tc = new TestClone(4,5); TestClone tcCloned = (TestClone) tc.clone(); System.out.println("a from tc " + tc.a); System.out.println("a from tcCloned " + tcCloned.a); } } /* * In Java object can be created in following ways... * 1. New Keyword * 2. newInstance() method * 3. clone() method * 4. Factory Method. */