Override clone judiciouslyA class that implements cloneable interface is expected to provide a fully functioning clone method and make the clone method public (Object class provide only a protected implementation of clone method). Clone creates an object without invoking the constructor.
1. If you override clone method in a non-final class, you should return an object obtained by invoking super.clone. So internally if all classes do it, Object’s clone method will be called creating the instance of the right class.
2. It is legal for an overriding method’s return type to be a subclass of the overridden method’s return type. This allows the overriding method to provide more information about the returned object and eliminates the need of casting in the client.
3. Clone method functions as another constructor. You must ensure that it doesn’t harm original object and that it properly establishes invariants on the clone. Clone method should always do a deep-copy wherever it makes sense. E.g. in case of a stack, clone method will copy only the size variable but not the actual elements (it will reference the same object. So you need to clone the array/list also.)
4. Providing clone methods will become difficult when there are final modifier variables in a class. This is because, after cloning you might want to make the variable reference a new value (or at least the cloned value) which might not be possible.
5. Clone method should internally use only private methods and final methods.
6. It is always preferable to use copy constructor or static factory than fixing the complexity of clone method.
Consider implementing Comparable
Comparable interface provides a natural ordering of the objects of a class. Equals() tells whether two objects are equal or not, whereas comparable tells the ordering of the two objects.
- By implementing Comparable interface, you can make use of a lot of existing generic algorithms and collection implementation that depend on this interface.
- CompareTo method can return a negative value, zero, or positive value as this object is less than, or equal, or greater than the specified object.
- You should make sure that sign of x.compareTo(y) = opposite sign of y.compareTo(x). Symmetry, Reflexivity, andTranslative relationship should also hold.
- Similar to equals(), there is no way that you can add a value component by subclassing.
- Unlike equals(), the parameter of the compareTo is not an Object, but the instance of the specific class itself.
I have taken these points from the book "Effective Java" which I consider as a MUST READ book for every JAVA developer.
No comments:
Post a Comment