Saturday 20 January 2018

oop - Why is the clone() method protected in java.lang.Object?

itemprop="text">

What is the specific reason that href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#clone%28%29"
rel="noreferrer">clone() is defined as protected
in java.lang.Object?


class="post-text" itemprop="text">
class="normal">Answer



The fact
that clone is protected is extremely dubious - as is the fact that the
clone method is not declared in the
Cloneable interface.



It
makes the method pretty useless for taking copies of data because you
cannot
say
:




if(a
instanceof Cloneable) {
copy = ((Cloneable)
a).clone();
}


I
think that the design of Cloneable is now largely
regarded as a mistake
(citation below). I would normally want to be able
to make implementations of an interface Cloneable but
not necessarily make the interface
Cloneable
(similar to the use of
Serializable). This cannot be done without
reflection:



ISomething i =
...
if (i instanceof Cloneable) {

//DAMN! I Need to know
about ISomethingImpl! Unless...
copy = (ISomething)
i.getClass().getMethod("clone").invoke(i);
}




Citation From Josh Bloch's Effective Java: />"The Cloneable interface was intended as a mixin interface for objects to
advertise that they permit cloning. Unfortunately it fails to serve this purpose ...
This is a highly atypical use of interfaces and not one to be emulated ... In order for
implementing the interface to have any effect on a class, it and all of its superclasses
must obey a fairly complex, unenforceable and largely undocumented
protocol
"




No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...