Using the clone method

Hi

I have been doing some reading but not sure if I have understood things very well. Can somebody please confirm the following:

1)Examples of Immutable objects are int, char, string etc andn examples of mutable objects are data and collections and your own classes which may use collections.

2)The object clone() method will only give you a perfect clone if

a)implement the clonable interface

b)override the class and make it public instead of the default protected

c)manually set the values of mutable objects e.g. copy.vectorvariable = (Vector)this.getVector();

Please confirm

[630 byte] By [javakida] at [2007-10-2 21:05:37]
# 1

> Hi

>

> I have been doing some reading but not sure if I have

> understood things very well. Can somebody please

> confirm the following:

>

> 1)Examples of Immutable objects are int, char, string

> etc andn examples of mutable objects are data and

> collections and your own classes which may use

> collections.

Incorrect. An int & a char are primitives, not objects. Immutable objects basically are any object that doesn't have mutator methods that allow you to change its internal state.

>

> 2)The object clone() method will only give you a

> perfect clone if

> a)implement the clonable interface

> b)override the class and make it public instead of

> the default protected

> c)manually set the values of mutable objects e.g.

> copy.vectorvariable = (Vector)this.getVector();

Incorrect on (c). If the object has mutable sub-objects (member objects), you must clone them as well, not just copy references to them.

>

> Please confirm

Dick_Adamsa at 2007-7-13 23:50:57 > top of Java-index,Java Essentials,Java Programming...
# 2

Hope I have understood you well.

1. Its compulsory that you implement the cloneable interface in order to do a proper clone and make it identify itself.

2. The class needs to be public.

3. You don't have to set values manually in case of primitive datatypes. But in case you have object references within the class, they too better implement the cloneable interface. Also collections needs to be iterated and objects within it cloned manually.

Maybe you might wanna try out the deepClone() method.

Hope this helps.

Pradyuta at 2007-7-13 23:50:57 > top of Java-index,Java Essentials,Java Programming...