Sie sind auf Seite 1von 2

package newclone;

import java.util.Date;

class TestClone implements Cloneable {


int a;
double b;
Date d;
TestClone()
{
a=10;
b=20;
d=new Date();
}
void setdate()
{
d.setDate(20);
}

public Object cloneTest() {


try {
// call clone in Object.
/* deep cloning
TestClone t=(TestClone)super.clone();
t.d = (Date)d.clone();
return t;*/
// shallow cloning
return super.clone();
} catch(CloneNotSupportedException e) {
System.out.println("Cloning not allowed.");
return this;
}
}
}

public class Newclone {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
TestClone x1 = new TestClone();
TestClone x2;
x2 =(TestClone) x1.cloneTest();
System.out.println("x1: " + x1.a + " " + x1.b + x1.d);
System.out.println("x2: " + x2.a + " " + x2.b + x2.d);
x1.a=40;
x1.b=50;
x1.setdate();
System.out.println("x1: " + x1.a + " " + x1.b + x1.d);
System.out.println("x2: " + x2.a + " " + x2.b + x2.d);

}
}
/* output
* deep copy
* x1: 10 20.0Wed Jul 31 20:26:38 IST 2013
x2: 10 20.0Wed Jul 31 20:26:38 IST 2013
x1: 40 50.0Sat Jul 20 20:26:38 IST 2013
x2: 10 20.0Wed Jul 31 20:26:38 IST 2013

*/

/* shallow copy
* x1: 10 20.0Wed Jul 31 20:27:26 IST 2013
x2: 10 20.0Wed Jul 31 20:27:26 IST 2013
x1: 40 50.0Sat Jul 20 20:27:26 IST 2013
x2: 10 20.0Sat Jul 20 20:27:26 IST 2013
*/

Das könnte Ihnen auch gefallen