Why Cloneable interface at the first place ?
A major problem with marker interfaces is that an interface defines a contract for implementing classes, and that contract is inherited by all subclasses. This means that you cannot unimplement a marker.Java needs a way to discriminate whether a class is Cloneable or not. Hence
Cloneable
interface
is a marker interface.
Why is #clone() not in the Cloneable interface ?
First, if the class of this object does not implement the interfaceCloneable
, then a
CloneNotSupportedException
is thrown.So why define the
clone
method there in the first place? Surely if a method can only be used
when an interface is present, you'd put the method in the interface. The Cloneable
interface
itself is empty; it is just a marker interface used by Java to ensure that using the clone method is
legal.The cloning contract in Java dictates that each clone implementation must first obtain the cloned instance from
super.clone()
. This creates a chain that always ends with the call to
Object.clone
, and that method contains magical native-level code that makes a
binary copy of the underlying raw struct which represents the Java object. If this mechanism didn't exist,
clone would fail to be polymorphic: the Object.clone
method produces an instance of whatever
class it is called on; this cannot be reproduced without native code.This is why the
Object.clone
method could not have been avoided. Cloneable could have contained
a clone method, but it would create issues regarding the throws clause. The way it stands you are free to
declare clone with no declared exceptions, or to declare arbitrary exceptions. This flexibility would not be
possible if the method was already declared in the interface.
Why not create a Cloneable class rather than marker interface?
Now if the Cloneable would have been a class then any other class which wanted to be cloned would have to extend Cloneable. Right? But Java does not support multiple inheritance, so a class that wanted to be Cloneable as well as extend some Parent would fail. Hence not a class.Why is clone() method protected in Object?
If it would have been public it would have created all sorts of doubts.Why is Java's Cloneable Interface Not Generic?
The Cloneable interface doesn't contain any members. What would be the point of making it generic?What is the best way to implement clone method?
Your clone method should always call super.clone so that object can be cloned via a magical method defined in the Object class. There should not be any new object creation logic available in clone method.Clone Method Implementation
Post a Comment
Post a Comment