java - How to create an object using same type of object -
i wonder if possible new instance of object, using other object of same type.
public class vegetable{ private int ... //a lot of fields public vegetable(vegetable v) { //some magic here } }
i looking option, wouldn't copy each single field manually in constructor, rather use super(v).
java not provide default copy constructor.
however, java provide method object.clone()
. can call on instances of classes implement cloneable. otherwise, throw clonenotsupportedexception.
the default implementation creates shallow copy. if object contains references other objects, references copied. not want. create deeper, more independent copy, can extend default implementation.
you can create own copy constructor, , useful. however, unlike clone()
, copy constructor not necessary create instance of same class. copy constructor class t create t, if it's passed instance of subclass of t.
Comments
Post a Comment