A First Look at the clone Method Every object inherits a method named clone

A first look at the clone method every object

This preview shows page 21 - 25 out of 25 pages.

A First Look at the clone Method Every object inherits a method named clone from the class Object The method clone has no parameters It is supposed to return a deep copy of the calling object However, the inherited version of the method was not designed to be used as is Instead, each class is expected to override it with a more appropriate version
Image of page 21
A First Look at the clone Method If a class has a copy constructor, the clone method for that class can use the copy constructor to create the copy returned by the clone method public Sale clone() { return new Sale(this); } and another example: public DiscountSale clone() { return new DiscountSale(this); }
Image of page 22
Pitfall: Limitations of Copy Constructors Although the copy constructor and clone method for a class appear to do the same thing, there are cases where only a clone will work For example, given a method badcopy in the class Sale that copies an array of sales If this array of sales contains objects from a derived class of Sale (i.e., DiscountSale ), then the copy will be a plain sale, not a true copy b[i] = new Sale(a[i]); //plain Sale object
Image of page 23
Pitfall: Limitations of Copy Constructors However, if the clone method is used instead of the copy constructor, then (because of late binding) a true copy is made, even from objects of a derived class (e.g., DiscountSale ): b[i] = (a[i].clone());//DiscountSale object The reason this works is because the method clone has the same name in all classes, and polymorphism works with method names The copy constructors named Sale and DiscountSale have different names, and polymorphism doesn't work with methods of different names
Image of page 24
The end Important to do at home : - read chapter 8 pages 506-531
Image of page 25

You've reached the end of your free preview.

Want to read all 25 pages?

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture