Created
February 28, 2017 05:58
-
-
Save bansalayush/f1939fd94eef1757f0d59ecef78add2b to your computer and use it in GitHub Desktop.
Cloning example and concept
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Cloning creates an exact copy of the object | |
* While using = as in the example it creates a reference to same memory location but with different name | |
*/ | |
import java.io.PrintStream; | |
public class CloneTest { | |
public static void main(String[] arrstring) throws Exception { | |
/*t1*/TestClass testClass1 = new TestClass(8798, 540.321); | |
/*t2*/TestClass testClass2 = (TestClass)testClass1.clone(); | |
/*t3*/TestClass testClass3 = testClass1; | |
System.out.println("\nt1");testClass1.print(); | |
System.out.println("\nt2");testClass2.print(); | |
System.out.println("\nt3");testClass3.print(); | |
System.out.println("\n Changing value of testClass1"); | |
testClass1.a=1234; | |
System.out.println("\nt1");testClass1.print(); | |
System.out.println("\nt2");testClass2.print(); | |
System.out.println("\nt3");testClass3.print(); | |
System.out.println("\n Changing value of testClass2"); | |
testClass2.a=5678; | |
System.out.println("\nt1");testClass1.print(); | |
System.out.println("\nt2");testClass2.print(); | |
System.out.println("\nt3");testClass3.print(); | |
System.out.println("\n Changing value of testClass3"); | |
testClass3.a=9876; | |
System.out.println("\nt1");testClass1.print(); | |
System.out.println("\nt2");testClass2.print(); | |
System.out.println("\nt3");testClass3.print(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TestClass | |
implements Cloneable { | |
int a; | |
double b; | |
public TestClass(int a ,double b) { | |
this.a = a; | |
this.b = b; | |
} | |
public void print() | |
{ | |
System.out.println("a=" +a+ " b=" + b); | |
} | |
public Object clone() | |
{ | |
try{ | |
return (TestClass)super.clone(); | |
} | |
catch(Exception e) | |
{ | |
System.out.println(e.toString()); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment