Java Reference
In-Depth Information
whichever is appropriate; similarly, all classes for instance variables in DataClass
should follow the model of Displays 13.7 or 13.8 , and so forth for classes for instance
variables inside of classes all the way down. You want every class in sight and every class
used in every class in sight to follow the model of Displays 13.7 or 13.8.
The same basic technique applies if your class is derived from some class other than
Object , except that, in this case, there normally is no required exception handling. To
implement the Cloneable interface in a derived class with a base class other than Object ,
the details are as follows: The base class must properly implement the Cloneable
interface, and the derived class must take care of any mutable class instance variable
added in the definition of the derived class. These new mutable class instance variables are
handled by the technique shown in Display 13.8 for the instance variable someVariable .
As long as the base class properly implements the Cloneable interface, including defining
the clone method as we are describing, then the derived class's clone method need not
worry about any inherited instance variables. Also, usually, you do not need to have try
and catch blocks for CloneNotSupportedException because the base class clone
method, super.clone() , normally catches all its CloneNotSupportedException s,
so super.clone() will never throw a CloneNotSupportedException . (See Self-Test
Exercise 15 for an example.)
Self-Test Exercises
12. Modify the following class defi nition so it correctly implements the Cloneable
interface (all the instance variables are shown):
public class StockItem
{
private int number;
private String name;
public void setNumber( int newNumber)
{
number = newNumber;
}
...
}
13. Modify the following class defi nition so it correctly implements the Cloneable
interface (all the new instance variables are shown):
public class PricedItem extends StockItem
{
private double price;
...
}
 
Search WWH ::




Custom Search