Java Reference
In-Depth Information
Atlanta Boston Savannah Tampa
54623239292 432232323239292 2323231092923992
The program creates an array of strings (line 5) and invokes the
sort
method to sort
the strings (line 6). The program creates an array of
BigInteger
objects (lines 11-13) and
invokes the
sort
method to sort the
BigInteger
objects (line 14).
You cannot use the
sort
method to sort an array of
Rectangle
objects, because
Rectangle
does not implement
Comparable
. However, you can define a new rectangle
class that implements
Comparable
. The instances of this new class are comparable. Let this
new class be named
ComparableRectangle
, as shown in Listing 13.9.
L
ISTING
13.9
ComparableRectangle.java
1
public class
ComparableRectangle
extends
Rectangle
2
implements
Comparable<ComparableRectangle> {
implements
Comparable
3
/** Construct a ComparableRectangle with specified properties */
4
public
ComparableRectangle(
double
width,
double
height) {
5
super
(width, height);
6 }
7
8 @Override
// Implement the compareTo method defined in Comparable
9
public int
compareTo(ComparableRectangle o) {
implement
compareTo
10
if
(getArea() > o.getArea())
11
return
1
;
12
else if
(getArea() < o.getArea())
13
return
-1
;
14
else
15
return
0
;
16 }
17
18 @Override
// Implement the toString method in GeometricObject
19
public
String toString() {
implement
toString
20
return super
.toString() +
" Area: "
+ getArea();
21 }
22 }
ComparableRectangle
extends
Rectangle
and implements
Comparable
, as shown
in Figure 13.5. The keyword
implements
indicates that
ComparableRectangle
inher-
its all the constants from the
Comparable
interface and implements the methods in the
interface. The
compareTo
method compares the areas of two rectangles. An instance of
ComparableRectangle
is also an instance of
Rectangle
,
GeometricObject
,
Object
,
and
Comparable
.
GeometricObject
«interface»
java.lang.Comparable<ComparableRectangle>
+compareTo(o: ComparableRectangle): int
Rectangle
ComparableRectangle
F
IGURE
13.5
ComparableRectangle
extends
Rectangle
and implements
Comparable
.
Search WWH ::
Custom Search