Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.help > #1192

Re: clone() and Cloneable

From markspace <-@.>
Newsgroups comp.lang.java.help
Subject Re: clone() and Cloneable
Date 2011-10-05 09:24 -0700
Organization A noiseless patient Spider
Message-ID <j6i0b3$ffm$1@dont-email.me> (permalink)
References <9852a7f5-75e0-49e9-9538-93824d185421@b6g2000vbz.googlegroups.com>

Show all headers | View raw


On 10/5/2011 5:44 AM, John Goche wrote:
>
> Hello,
>
> What are the advantages of implementing the Cloneable
> interface as opposed to a standard copy constructor perhaps
> called clone() with no Cloneable interface in the class declaration?
>

One important difference is clone() is polymorphic.

public class Point {
   private double x, y;
   // getters/setters elided.
}

public class ColorPoint extends Point {
   Color color;
   // getter/setter elided.
}

If you make a copy constructor for Point, you have to do the same for 
ColorPoint.  But if you make Point Clonable, you don't have to do 
anything for ColorPoint.  Its private field will still be copied by the 
clone() call.

public class Point {
   private double x, y;
   // getters/setters elided.

   public Point clone() {
     try {
       return (Point) super.clone();
     } catch( CloneNotSupportedExcetpion x ) {
       // cannot happen
     }
   }

}

Now clone() is properly supported for all classes that inherit from 
Point.  Its children don't have to have any extra code to support 
clone() either, it's all done in the super class.  Using Java copy-like 
constructors (Java doesn't really have copy constructors like C++ does), 
you'll have to implement extra code in each child to support the copy.


Back to comp.lang.java.help | Previous | NextPrevious in thread | Find similar


Thread

clone() and Cloneable John Goche <johngoche99@googlemail.com> - 2011-10-05 05:44 -0700
  Re: clone() and Cloneable Roedy Green <see_website@mindprod.com.invalid> - 2011-10-05 06:28 -0700
  Re: clone() and Cloneable Lew <lewbloch@gmail.com> - 2011-10-05 06:58 -0700
  Re: clone() and Cloneable markspace <-@.> - 2011-10-05 09:24 -0700

csiph-web