Path: csiph.com!eternal-september.org!feeder.eternal-september.org!aioe.org!.POSTED!not-for-mail From: =?UTF-8?Q?Arne_Vajh=c3=b8j?= Newsgroups: comp.lang.java.programmer Subject: Re: Why it necessary to implement clonealbe interface? Date: Tue, 24 Nov 2015 19:49:59 -0500 Organization: Aioe.org NNTP Server Lines: 44 Message-ID: References: NNTP-Posting-Host: 1lM8B9/qdtKBc/uIRK2Gjw.user.speranza.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=gbk; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: abuse@aioe.org User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Thunderbird/38.3.0 X-Notice: Filtered by postfilter v. 0.8.2 Xref: csiph.com comp.lang.java.programmer:33196 On 11/24/2015 11:03 AM, Eric Sosman wrote: > On 11/24/2015 10:28 AM, Xue Feng wrote: >> A class has to implement cloneable interface, otherwise its object can >> not be cloned. IMO, it is enough that a class clone itself by inheriting >> the clone method from Object class. It is somewaht reduntant to >> implement cloneable interface. Actually, there is nothing in cloneable >> interface. Namely, it is defined as follows: >> >> interface cloneable { >> } >> >> I wonder the reason for this design. Any explanation? Thanks. > > Object's clone() is a protected method, so it can be called only > from a subclass of Object. Since every class descends from Object > this may not seem like much of a restriction, but it is: If classes > X and Y both inherit clone() from object, then X's clone() and Y's > clone() are also protected. X can call its own clone() and can call > Object's clone(), but it cannot call Y's clone -- because Y's clone() > is protected, and X is not a subclass of Y. Similarly, Y can call > its own clone() and Object's clone(), but cannot call X's clone(). > So, mere inheritance of the clone() method is not enough to make it > usable outside one branch of the inheritance tree. > > Also, Object's clone() throws CloneNotSupportedException if the > object being cloned is of a non-Cloneable class. The Cloneable > interface is a "marker," a notification that the class has provided > for its own cloning. (The "marker interface" pattern is unusual, and > some would even call it an anti-pattern, but cloning is an unusual > operation to begin with.) By implementing Cloneable, a class announces > to Java: "I have decided what it means to make a `clone' of my objects, > and have made arrangements to create such clones." Usually, the > arrangements involve overriding the inherited clone() so as to do > some class-specific things; the class might also choose to make its > overriding clone() method public. To this excellent explanation I would just like to add that today (today as in last decade) instead of a marker interfaces one would usually use an annotation. But Cloneable goes back to Java 1.0. Arne