The basic collection interfaces (List, Map, Set) do not extend Cloneable interface. This is done in order NOT to enforce Cloneability for concrete implementations.
All of the collection classes do implement Cloneable interface so they all are inherently Cloneable. Also Cloneable is a marker interface meaning it signals the compiler/JVM to do some additional work behind the curtain, so as make that object Cloneable.
Now my question is : What the situations where in you DO NOT want your object to be Cloneable?
Singleton is a good case. Another is anything where you have a reference to something on the system that you should only have ONE reference to. For example, a Stream. Having multiple objects point to the same input (or output) stream could cause all kinds of problems.
If you want to use clone(), consider creating a copy constructor instead.
If your class holds a huge chunk of data then you may not want it to be cloned to stop keeping multiple copy of a big chunk of data.
If you were to implement the Singleton pattern, you probably wouldn't want the resulting Singleton to be cloneable.
I wouldn't want to have cloneable threads :X
Neither cloneable resource classes or session beans
Related
Is there a way where I can prevent the parent class to be serialized?
When we do a serialization of the subclass all the way up till the parent class the serialization is performed.
Can I restrict the serialization of the parent classes and serialize the only sub class I am working on?
It is possible. Just declare your class as implements Externalizable and write exactly what you need in the writeExternal() method, taking care not to serialize anything from the superclass, and read exactly that back in the readExternal() method.
Or, just implement Serializable and provide your own readObject()/writeObject() methods, again taking care not to serialize anything from the superclass, and in this case also not calling defaultWriteObject() or defaultReadObject().
In both cases the actual serialization of the current class's data is entirely up to you.
Whilst it is technically possible to fine tune each level of inheritance on its own - even to the extent of excluding super class fields - you might want to step back here.
Basically there are two cases:
The super class does not have any fields / state. Then you have nothing to exclude anyway.
The super class has state, represented by fields of that class.
So how do you think to meaningfully address the second part? You see when you allow deserialisation without the data for the super class fields - that means that you might have to do a lot of additional testing. To make sure that super class methods don't throw exceptions - because all of a sudden fields are null instead of being initialized.
In other words: it is possible that "leaving out" all these values - you are creating objects which behave completely different. Are you prepared for handling all the effects of that?
Meanung: skipping super class fields requires you to interfere with serialization code. It might require a lot of additional testing effort. And what do you gain? A few bytes less of data transfer at runtime.
Beyond that: what is the purpose of an inheretance hierarchy that has 4 levels - but where the super class state is irrelevant?
So my non-answer: carefully consider if your idea is really the best OO design to solve the underlying requirements.
We all know state of an Object is value of it's attributes (instance variables), but if class doesn't has any attribute (no inherited attributes), what would be the state of an Object of such class.
There is a word for such objects - stateless.
There is no such thing as a Java class without a parent class. The default parent would be used, e.g. java.lang.Object.
At a minimum every instance of a class has two attributes: a reference address and a Class type. Note, not every class can be instantiated. There is also some space used in the ClassLoader and any String(s) may (or may not) be interned. This actual implementation might vary slightly on the specific version of the JDK and run-time platform, and additional optimizations can be added by the JIT. However, as a Java developer you are not responsible for this memory management and I would be wary of premature optimization.
first thing
any class we write in java will extend Object class by default if there is no extends written by the developer.
so each and every class will definitely have a parent with no doubt atleast Object class.
second
if you dont put any attributes in your class , obviously it will get all the instance variables except private gets inherited to your class.
so it will have atleast object state but it will not serve any purpose
An object with no data members and links to other objects is a stateless object and in this form can hardly be of any use.
This kind of classes can nevertheless be usefull, because of its methods. It can be...
a base for a further inheritance. It declares/defines some methods, that could be inherited by derived classes. This class will probably be an abstract class, having no objects at all (although not a condition)
a service class. It can define some methods, which in nature do not belong to concrete objects but are used by other objects. Like some all-purpose mathematical operations, a service that returns a current time or similar. These methods can be static, so again no instances are needed.
We call those object stateless. As the name suggests, they have no state.
Referring to other answers/comments, even though every Java object implicitly extends Object, mind that Object has no fields. So even though every object has a runtime address and class attributes, for all practical purposes you can still consider some objects stateless.
Next, it is definitely not true that stateless objects serve no purpose! You can use stateless object for:
1) Grouping functions with similar functionality, similar to java.lang.Math, which groups mathematical functions.
2) Passing functionality as a parameter, e.g. Comparator<T> can be used to sort objects that do not implement Comparable<T>, and it definitely needs no state.
Stateless objects are somehow similar to immutable objects: their state can never be changed and therefore they are always thread-safe.
You may also want to see JEE Stateless Session Beans which differentiate between a converstional state and an instance state.
Its always said its better to use a collection object as below
1) List st = new LinkedList();
2) Map mp = new HashMap();
Than
3) LinkedList st = new LinkedList();
4) HashMap mp = new HashMap();
I agree by defining as above (1,2) I can reassign the same variable (st,mp) to other objects of List, Map interface
But Here I cant use the methods that are defined only in LinkedList, Hashmap which is correct as those are not visible for List, Map . (Please correct me if am worng)
But if am defining a object of HashMap or LinkedList, I want to use it for some special functionality from these.
Then Why is it said the best way to create a collection object is as done in ( 1,2 )
Because most of the time you don't need the special methods. If you need the special methods, then obviously you need to reference the specific type.
Lesson for today: Don't blindly apply programming principles without using your own brain.
But if am defining a object of HashMap or LinkedList, I want to use it for some special functionality from these.
In that case, you should absolutely declare the variable using the concrete class. That's fine.
The point of using the interface instead is to indicate that you only need the functionality exposed by that interface, leaving you open to potentially change implementation later. (Although you'd need to be careful of the performance and even behavioural implications of which concrete implementation you choose.)
I agree by defining as above (1,2) I can reassign the same variable
(st,mp) to other objects of List,Map interface
Yes, it's a general practice called programming against interfaces.
But Here I cant use the methods that are defined only in LinkedList,
Hashmap which is correct as those are not visible for List,Map .
(Please correct me if am worng)
No, you are right.
But if am defining a object of HashMap or LinkedList, I want to use it
for some special functionality from these.
Then Why is it said the best way to create a collection object is as
done in ( 1,2 )
This isn't the best way. If you need to use specific methods of those classes you need the reference to the concrete type. If you need to use those collections from a client class that is not supposed to know the internal implementation than it's better to expose only the interface.
Through interfaces you define service contracts. As you say, should you change the lower implementation of a given interface, you can do it flawlesly without any impact on your current code.
If you need any particular behaviour of the particular classes it's absolutely right to use them. Maps usually extend the AbstractMap class that itself implements Map, making the subclasses inherit those methods.
Of course, many classes throw IllegalOperationException on some defined methods of the Map interface, so that implementation type change is not always flawless (but in most cases, it is, because each map has a particular asset that makes it the most appropiate choice for a given context).
Use the type that suits you, not the one that someone says it's the correct one. Every rule has exceptions.
Because if you use the interface to access the collections, you are free to change the implementation. Eg use a ArrayList instead LinkedList, or a synchronized version of it.
This mostly applies to cases where you have a Collection in a public interface of the class, internally i wouldn't bother, just use what you need.
This question already has answers here:
clone() vs copy constructor vs factory method?
(10 answers)
Closed 8 years ago.
clone method vs copy constructor in java. which one is correct solution. where to use each case?
Clone is broken, so dont use it.
THE CLONE METHOD of the Object class
is a somewhat magical method that does
what no pure Java method could ever
do: It produces an identical copy of
its object. It has been present in the
primordial Object superclass since the
Beta-release days of the Java
compiler*; and it, like all ancient
magic, requires the appropriate
incantation to prevent the spell from
unexpectedly backfiring
Prefer a method that copies the object
Foo copyFoo (Foo foo){
Foo f = new Foo();
//for all properties in FOo
f.set(foo.get());
return f;
}
Read more
http://adtmag.com/articles/2000/01/18/effective-javaeffective-cloning.aspx
Have in mind that clone() doesn't work out of the box. You will have to implement Cloneable and override the clone() method making in public.
There are a few alternatives, which are preferable (since the clone() method has lots of design issues, as stated in other answers), and the copy-constructor would require manual work:
BeanUtils.cloneBean(original) creates a shallow clone, like the one created by Object.clone(). (this class is from commons-beanutils)
SerializationUtils.clone(original) creates a deep clone. (i.e. the whole properties graph is cloned, not only the first level) (from commons-lang), but all classes must implement Serializable
Java Deep Cloning Library offers deep cloning without the need to implement Serializable
clone() was designed with several mistakes (see this question), so it's best to avoid it.
From Effective Java 2nd Edition, Item 11: Override clone judiciously
Given all of the problems associated with Cloneable, it’s safe to say
that other interfaces should not extend it, and that classes
designed for inheritance (Item 17) should not implement it. Because of
its many shortcomings, some expert programmers simply choose never to
override the clone method and never to invoke it except, perhaps, to
copy arrays. If you design a class for inheritance, be aware that if
you choose not to provide a well-behaved protected clone method, it
will be impossible for subclasses to implement Cloneable.
This book also describes the many advantages copy constructors have over Cloneable/clone.
They don't rely on a risk-prone extralinguistic object creation mechanism
They don't demand unenforceable adherence to thinly documented conventions
They don't conflict with the proper use of final fields
They don't throw unnecessary checked exceptions
They don't require casts.
All standard collections have copy constructors. Use them.
List<Double> original = // some list
List<Double> copy = new ArrayList<Double>(original);
Keep in mind that the copy constructor limits the class type to that of the copy constructor. Consider the example:
// Need to clone person, which is type Person
Person clone = new Person(person);
This doesn't work if person could be a subclass of Person (or if Person is an interface). This is the whole point of clone, is that it can can clone the proper type dynamically at runtime (assuming clone is properly implemented).
Person clone = (Person)person.clone();
or
Person clone = (Person)SomeCloneUtil.clone(person); // See Bozho's answer
Now person can be any type of Person assuming that clone is properly implemented.
See also: How to properly override clone method?. Cloning is broken in Java, it's so hard to get it right, and even when it does it doesn't really offer much, so it's not really worth the hassle.
Great sadness: neither Cloneable/clone nor a constructor are great solutions: I DON'T WANT TO KNOW THE IMPLEMENTING CLASS!!! (e.g. - I have a Map, which I want copied, using the same hidden MumbleMap implementation) I just want to make a copy, if doing so is supported. But, alas, Cloneable doesn't have the clone method on it, so there is nothing to which you can safely type-cast on which to invoke clone().
Whatever the best "copy object" library out there is, Oracle should make it a standard component of the next Java release (unless it already is, hidden somewhere).
Of course, if more of the library (e.g. - Collections) were immutable, this "copy" task would just go away. But then we would start designing Java programs with things like "class invariants" rather than the verdammt "bean" pattern (make a broken object and mutate until good [enough]).
New to Java. Learning it while working on an Android app. I am implementing a Comparator to sort a list of files and the android docs say that a Comparator should implement Serializable:
It is recommended that a Comparator implements Serializable.
This is the Serializable interface here.
I just want to sort a list of files. Why should I implement this or what even is the reason why it should be for any Comparator?
This is not just an Android thing, the Java SDK has the same recommendation:
Note: It is generally a good idea for comparators to also implement java.io.Serializable, as they may be used as ordering methods in serializable data structures (like TreeSet, TreeMap). In order for the data structure to serialize successfully, the comparator (if provided) must implement Serializable.
So the idea is that because a TreeMap is serializable, and the TreeMap can contain a Comparator, it would be good if the Comparator is also serializable. The same applies for all elements in the collection.
You can safely ignore this unless you use serialization in that way.
Serializeable is a blank interface. It does not contain any methods. So, to implement it, all you need to say is implements Serializable in a class. It's not a huge burden on you. If you extend Comparator, you don't even need to implement Serializable because the super class does that for you, and then you don't need to do anything at all to implement Serializable.
When something implements Serializable, that means the object can be turned into a byte array at will. This is used for transmission over the Internet, storage in a file, etc. Speaking very roughly, the way serialization works for an object, by default, is to take every object referenced by the object you're trying to serialize, turn each such object into a byte array (i.e. invoke serialization on it recursively), and concatenate the byte arrays to produce a byte array that represents the overall object.
Now, why should a Comparator implement Serializable? Let's say you wish to serialize a TreeMap or some other ordered Collection. The goal of serialization is to provide a complete representation of an object. Collections like TreeMap have a Comparator object in them, so to be able to produce a byte array that captures every aspect of such collections, you need to be able to save the Comparator as a byte array too. Hence, Comparator needs to be Serializable so that other things can be properly serialized.
This should help you out : http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html
Note: It is generally a good idea for comparators to implement java.io.Serializable, as they may be used as ordering methods in serializable data structures (like TreeSet, TreeMap). In order for the data structure to serialize successfully, the comparator (if provided) must implement Serializable.
To serialize an object in Java, both these conditions should be satisfied:
The class to which the instance belongs to must implement java.io.Serializable.
The members of the class should be serializable. If one or more of the members are not to be serialized, they should be marked as transient.
When any data structure uses a Comparator and you want that data structure to be serializable, point 2 (mentioned above) compels the comparator to implement serializable.
i have seen in Java 5 API
Link to java 5 APT
which stated that by implementing Comparator doesn't mean to implement Serializable interface anyways, so one has to explicitly pay attention to get Serializable in some customarily created Comparator class