Hi, In my development experience I have never once felt the need to clone my objects. I am wondering why it is required. Can someone give me some scenarios where a problem cannot be solved without cloning. Thanks in advance. Das
-The following example (see code at message bottom) is the most common example I have seen on cloning. The problem of this example (and most of the clone examples), is that it violates the spirit of object-oriented programming since it breaks encapsulation... -One good reason you may need to clone an object is to save the state of an object at a given time to restore it later on. In specific situations, it may be overruled by Serialization. -In his excellent book, Java Performance Tuning, J.Shirazi (O'Reilly ed.) compares the object creation with constructor or duplication with clone in terms of performance. An example is given on the factory design pattern. -You may see also the also excellent book of Joshua Bloch (I just forgot the title right now - Effective java?) which also deals with this purpose. Here is the example code highlighting the problem (comments have been added following Suprakash's message) :
[This message has been edited by Wilfried LAURENT (edited October 16, 2001).] [This message has been edited by Wilfried LAURENT (edited October 16, 2001).]
Joined: Nov 26, 2000
Hi Wilfried, Thanks for you reply. Can you also post the source of the Dimension class. Sorry if I sound thick, but I'm not sure I understand the problem that the example you have given is trying to solve. Also, when you are trying to save the state of an object, when is serialization not an option? Thanks, Das
Joined: Jul 13, 2001
Originally posted by Suprakash Das: Can you also post the source of the Dimension class. Sorry if I sound thick, but I'm not sure I understand the problem that the example you have given is trying to solve.
The Dimension class is the standard java.awt.Dimension. I was not trying to solve a problem but to highlight the problem. In the given example, you are breaking encapsulation while returning a reference on the Dimension instance. The client can modify this instance, set x to -1, without ImmutableDimension is aware of that change. If ImmutableDimension then tries to paint a rectangle with this Dimension it will fail with exception. If, instead of returning the instance of Dimension, you return a clone (copy) of this instance, the client can do whatever if wants to this instance, it will not affect the instance of the Dimension attribute in the ImmutableDimension class.
Also, when you are trying to save the state of an object, when is serialization not an option?