Java Reference
In-Depth Information
The remaining getters and setters have not been shown; however, they all follow the same
form as the
getComposer
and
setComposer
methods shown earlier.
Tip
Most IDEs have the ability to automatically generate getters and setters for you, including generating
rudimentary Javadoc comments. After using such facilities, you can go to each generated method, add any
required business logic, and modify the Javadoc comments to suit.
■
One last point worth considering is whether we would ever want to compare two
instances of a
DVD
to see if they are the same. In a stand-alone application, we might consider
allowing only a single instance of each
DVD
object to be created, in which case we would be
able to check that they were equal by using the
==
comparison. However, since we might be
getting multiple copies of the same
DVD
record over a network, each copy will be deserialized
into a separate instantiation of the
DVD
class, so we cannot use the
==
comparator. We should
therefore look at overriding the
equals
method of the
Object
class.
416 public boolean equals(Object aDvd) {
417 if (! (aDvd instanceof DVD)) {
418 return false;
419 }
420
421 DVD otherDvd = (DVD) aDvd;
422
423 return (upc == null) ? (otherDvd.getUPC() == null)
424 : upc.equals(otherDvd.getUPC());
425 }
At line 417, we ensure that we have been given an instance of
DVD
to compare against.
Once we have confirmed this—and only when we have confirmed this—we can convert the
supplied object into an object of type
DVD
, as shown in line 421. Finally, in lines 423 and 424 we
utilize the fact that UPC numbers are unique for DVDs, and compare the UPC numbers.
■
Note
Lines 423 and 424 use a ternary operator to determine whether to return true or false. Everyone
has their own opinion as to whether ternary operators increase or decrease readability. This is something
you will have to decide for yourself, possibly on a case-by-case basis. In this particular case, we believe it
improves readability, compared with the alternative:
if (upc == null) {
return otherDVD.getUPC() == null;
} else {
return upc.equals(otherDVD.getUPC());
}