java - Copying object fields -
what best way of copying classes when need have 2 independent variables? have simple class:
public class myclass { boolean = false; string b= "not empty"; }
do need make method :
assign(myclass data ) { a= data.a; b= data.b; }
is there automatic method copy (duplicate) objects in java?
do need make method :
pretty close. instead of making method, should make constructor. such constructors called copy constructor, , create them this:
myclass(myclass data) { = data.a; b = data.b; }
and create copy of instance, use constructor this:
myclass obj1 = new myclass(); myclass obj2 = new myclass(obj1);
copy constructor can tedious:
using copy constructor create deep-copy can tedious, when class has mutable fields. in case, assignment create copy of reference, , not object itself. have create copy of fields (if want deep copy). can go recursive.
a better way create deep copy serialize , deserialize object.
why not use clone()?
addition of clone()
method in object class big mistake, imo. should avoid using cloning objects.
- for one, use method, have implement
cloneable
interface, surprise doesn't haveclone()
method. in fact, it's marker interface. - return type of
object#clone()
methodobject
. so, means can return instance of unrelated class, leading code potentialclasscastexception
@ runtime.
see also:
Comments
Post a Comment