Java Reference
In-Depth Information
public
Address ()
{
}
public
Address( String streetName ,
int
number)
{
this
. streetName = streetName ;
this
. number = number ;
}
public
String toString()
{
return
number +
""
+ streetName ;
}
public void
changeAddress(String streetName ,
int
number)
{
this
. streetName = streetName ;
this
. number = number ;
}
public
Object clone ()
throws
CloneNotSupportedException
{
Address result = (Address)
super
.clone();
result .streetName =
new
String(streetName) ;
return
result ;
}
}
When we execute the program, we get:
Superwoman lives at 123 Main
.Thisismore
desirable behavior. The address of the fictional character
c1
is changed, but this does not
lead to the change of the address of fictional character
c2
. After all, the clone of Superwoman
may live down the street from the original Superwoman. The
clone
method inside the
FictionalCharacter
class uses the
clone
method of the
Object
class. The latter method
just copies the data. Since the returned object must be of type
Object
, it needs to be
explicitly cast to a
FictionalCharacter
. In addition, we make a copy of the address object
by calling the
clone
method on the address object. Note that the
Address
class is now
rewritten to support the
clone
method.
8.13 Comparing Objects for Equality
Now that we know how to clone fictional characters, it is reasonable to ask ourselves
when two fictional characters are equal. In Java, the following code will compile.
Superhero s1 =
new
Superhero(
"Superman"
,5,5) ;
Superhero s2 =
new
Superhero(
"Superman"
,5,5) ;
if
(s1 == s2)
{
...
}
One might anticipate that the condition inside the
if
statement will be true because the two
superheroes have the same
name
,
goodPower
,and
respect
. However, when “==” is used
to compare two objects, only their addresses are compared. In the above case, we clearly
have two distinct objects, and therefore the condition inside the
if
statement will be false.
If we need access to a more meaningful way of comparing two objects for equality, then
we need to override the
equals
method of the
Object
class. Since the
equals
method is