Programming and Problem Solving with Java

(やまだぃちぅ) #1
4.6 Abstraction | 181

As we saw earlier in this chapter, we often want to compare objects so that we can make
decisions based on their values. Thus we should add responsibilities that compare two
names for equality or inequality. Inequality is based on alphabetical ordering by last name,
first name, and middle name.


Now that we’ve defined a more general set of responsibilities for the Nameclass, we have
a class that can be imported and reused by a wide range of user code. The abstraction is rea-
sonably complete, and we’ve identified some features that could be added to extend it even
further. The use of methods to implement the entire interface encapsulates the abstraction
so that user code cannot take advantage of special features of the implementation.
Here is an implementation of the new Nameclass. It looks like quite a bit of code, but if
you focus on each method separately, you can see that the class is broken into many pieces,
each of which is quite simple. Pay especially close attention to the methods that implement
the comparisons. They use the equalsand compareTomethods associated with the String
class to compare the names. Recall that the ==operator tests whether reference variables re-
fer to the same place in memory. To compare the actual contents of two objects, we use
methods such as these. Also note that our comparison methods convert the names to all up-
percase letters as discussed previously.


importjava.io.*; // Package for stream readers


//**
// This class provides a basic name object. The default constructor
// requests that a name be entered from System.in. A second constructor
// allows creation of a name from strings. Methods return the name
// in various formats.
//**
className
// This class defines a name consisting of three parts
{
String first; // Person's first name
String last; // Person's last name
String middle; // Person's middle name


// Gets a name from System.in
publicName() throwsIOException
{
BufferedReader in; // Input stream for strings
// Instantiate in using System.in
in = new BufferedReader(new InputStreamReader(System.in));

equals(Name otherName) returns boolean
compareTo(Name otherName) returns int
Free download pdf