Java Reference
In-Depth Information
sections that follow this example document the default implementation of each
method and explain why you might want to override it.
The example uses a lot of the extended features of the type system that we met last
chapter. First, it implements a parameterized, or generic, version of the
Comparable
interface. Second, the example uses the
@Override
annotation to emphasize (and
have the compiler verify) that certain methods override
Object
.
Example 5-1. A class that overrides important Object methods
// This class represents a circle with immutable position and radius.
public
class
Circle
implements
Comparable
<
Circle
>
{
// These fields hold the coordinates of the center and the radius.
// They are private for data encapsulation and final for immutability
private
final
int
x
,
y
,
r
;
// The basic constructor: initialize the fields to specified values
public
Circle
(
int
x
,
int
y
,
int
r
)
{
if
(
r
<
0
)
throw
new
IllegalArgumentException
(
"negative radius"
);
this
.
x
=
x
;
this
.
y
=
y
;
this
.
r
=
r
;
}
// This is a "copy constructor"--a useful alternative to clone()
public
Circle
(
Circle
original
)
{
x
=
original
.
x
;
// Just copy the fields from the original
y
=
original
.
y
;
r
=
original
.
r
;
}
O
n
// Public accessor methods for the private fields.
// These are part of data encapsulation.
public
int
getX
()
{
return
x
;
}
public
int
getY
()
{
return
y
;
}
public
int
getR
()
{
return
r
;
}
// Return a string representation
@Override
public
String
toString
()
{
return
String
.
format
(
"center=(%d,%d); radius=%d"
,
x
,
y
,
r
);
}
// Test for equality with another object
@Override
public
boolean
equals
(
Object
o
)
{
// Identical references?
if
(
o
==
this
)
return
true
;
// Correct type and non-null?
if
(!(
o
instanceof
Circle
))
return
false
;
Circle
that
=
(
Circle
)
o
;
// Cast to our type
if
(
this
.
x
==
that
.
x
&&
this
.
y
==
that
.
y
&&
this
.
r
==
that
.
r
)
return
true
;
// If all fields match
else
return
false
;
// If fields differ