Java Reference
In-Depth Information
changes in the method heading, this definition overrides the method
clone
inherited
from the class
Object
. As we noted in Chapter 7 , a change to a more permissive access,
such as from
protected
to
public
, is always allowed when overriding a method
definition. Changing the return type from
Object
to
Sale
is allowed because
Sale
(and every other class, for that matter) is a descendent class of the class
Object
. This
is an example of a covariant return type, as discussed in the subsection of Chapter 7
entitled “Changing the Return Type of an Overridden Method.”
The
clone
method for the
DiscountSale
class can be defined similarly:
public
DiscountSale clone()
{
return new
DiscountSale(
this
);
}
The definitions of the classes
Sale
and
DiscountSale
on the website that
accompanies this topic each include the method
clone
defined as we just described.
extra code
on website
PITFALL: Sometimes the
clone
Method Return Type Is
Object
Prior to version 5.0, Java did not allow covariant return types, and so did not
allow any changes whatsoever in the return type of an overridden method. In those
earlier versions of Java, the
clone
method for all classes had
Object
as its return
type. This is because the
clone
method for a class overrides the
clone
method of
the class
Object
, and the
clone
method of the class
Object
has a return type of
Object
. If you encounter a
clone
method for a class that was designed and coded
before version 5.0 of Java, the
clone
method will have a return type of
Object
.
When using such older
clone
methods, you will need to use a type cast on the value
returned by
clone
.
For example, suppose the class
OldClass
was defi ned before Java 5.0. If
original
is an object of the class
OldClass
, then the following will produce a
compiler error message:
OldClass copy = original.clone();
The problem is that
original.clone()
returns a value of type
Object
, while the
variable
copy
is of type
OldClass
. To correct the situation, you must add a type cast
as follows:
OldClass copy = (OldClass)original.clone();
(continued)