Home Demos Forum Research Guide
Viewing topic in forum 'general'
back to topic list

Cloning object
Hi

I have been trying to clone an object using the documented method like this :

x = clone y

but i get the message Objects cannot be cloned in this way, use the objects clone method.

How do i do this? I have tried y.clone() and also clone(y) but both cause compile errors. Does my object need to require a particular interface in order for it to be clonable ?

Thanks,

Phil
by philbeattie on 2016-02-17 11:20:36 (2 replies)

Just realised what i was doing wrong. I didnt know that you can only clone data types and arrays and not whole objects using the x = clone y notation.

by philbeattie on 2016-02-17 12:21:23
Hi Phil,

You're right, cloning an object is generally not permitted by the language. This is because object instances generally need to be linked against required interfaces so that they are later adaptable.

The correct way to "clone" an object is to create a new instance of the object and then pass in a reference to the old one as a parameter:


MyObject m = new MyObject()
m.copyFrom(x)
 


Within the copyFrom function you can then write appropriate code to acquire the necessary state from x. Note that the above code should be inside a component that *uses* MyObject, and never from the implementation of MyObject itself. That way the instance "m" can be properly linked to the required interface of the component that uses it, and then adapted later.

Hope that clarifies things!

Barry
by barry on 2016-02-17 15:38:32
© Francis Research Ltd. 2017