Monday, September 27, 2010



Why clone?

Sometimes you need to make a copy of an object. Most of the time the fact that Java uses references to objects is a great advantage because you don't have to worry about making copies of objects, but sometimes you need a copy.

  • Protect against changes. You need a copy to hand to someone you don't trust to leave the object unchanged.
  • In place of new. The standard way to make new objects is to use the new operator, which calls a class constructor. A different way to think about creating multiple objects of a "class" is to create on prototype and create new objects by copying this prototype, typically by calling on a factory method to create new objects. This is useful if different kinds of objects are distinguished by different parameter values.

    For example, you might want several kinds of arrowheads - filled, empty, diamonds, barbed, etc. With a little planning, code can be written to draw all of these types, differing only in parameter values (isFilled, pointAngle, barbAngle). Different types of graphical objects can simply be created once, and cloned to make a new objects of that "class".

The clone() method - and why you might want to override it

The Object class defines a clone() method that makes a shallow copy of an object.

Protected not public. Even if a shallow copy was sufficient, and it's often not, a user can't get to it because it's protected and not public, so only subclasses can see it, but no users! You can make it available by overriding it in your class and making it public -- you can always make an overridden method more visible that it was in the parent class.

No comments:

Post a Comment