fb

Ads

Pages

How to to get objective of duplicating an arbitrary object (Java) ?

You want to clone your object, you need to make it cloneable. To achieve
this, you need to do two things:
1. implement the interface Cloneable
2. override the method clone(), so that it
a. becomes public
b. calls super.clone()
c. if necessary, clones any members, or
d. if a member can't be cloned, creates a new instance.

Example:
 

public MyClass implements Cloneable {
int someNumber;
String someString;
public Object clone() {
// primitives and Strings are no
// problem
return super.clone();
}
}


In this case the method clone() of the class MyClass returns a new instance of
MyClass, where all members have exactly the same value. That means, the object
reference 'someString' points to the same object. This is called a shallow
copy. In many cases this is no problem. Strings are immutable and you do not
need a new copy. But if you need new copies of members, you have to do it in
the clone() method. Here is another simple example:


public class SomeMember implements Cloneable {
long someLong;

public Object clone() {
return super.clone();
}
}
public AnotherClass extends MyClass {
SomeMember someMember;
public Object clone() {
AnotherClass ac = (AnotherClass)(super.clone());
if (someMember != null) {
ac.someMember = (SomeMember)(someMember.clone());
}
return ac;
}
}

 
=>Note that the class AnotherClass, that extends MyClass, automatically becomes Cloneable, because MyClass is Cloneable. Also note, that super.clone() always returns an Object of the type of the actual object,
although the superclass doesn't know anything about that sub class. The reason is, that Object.clone() is a native method, which just allocates new memory for the new object and copies the bytes to that memory. Native code has it's own ways of finding out which type to return.

0 comments:

Post a Comment