Programming and Problem Solving with Java

(やまだぃちぅ) #1
6.6 Object-Oriented Implementation | 293

implicitly take their associated object as an argument and have access to its fields. In addi-
tion, they can receive values through the parameter list, as noted on the CRC card.
Class methods are used to implement responsibilities that are not associated with a
particular object, such as the Math.absmethod. They may also affect all the instances of a class.
For example, we can set the maximum score for all TestScoreobjects so that they can be
checked for errors. None of the responsibilities of the Phoneclass is appropriate for a class
method implementation.
We are ready to write the responsibilities of the Phoneclass as methods. We must con-
vert the responsibility names written as phrases into Java method identifiers. “Create itself”
becomes the class constructor Phone. “Know area code” becomes knowAreaCode, and “Know dig-
its” becomes knowDigits. “Number as digits” becomes asDigits, and “Number in print form”
becomes asString. “Are two numbers equal” becomes equals(Phone secondNumber).
The algorithms for knowledge responsibilities are so simple that we can go straight to
writing code. What about asDigits, the method that returns the number as 10 digits? We can
multiply the area code by 10,000,000 to shift the digits over and add the result to the num-
ber. How do we convert the area code and number to strings and insert hyphens as separa-
tors? Hyphens!Exactly how is the number as a string supposed to look? We often see a
telephone number written with two hyphens as follows: 512–441–2323. Thus we have to
break the number portion into two pieces: the first three digits and the last four digits. We
can use integer division and remainder to accomplish this separation. To compare two phone
numbers, we first compare the area codes. If they are not the same, the numbers are not equal.
If the area codes are the same, we then compare the numbers. If both the area codes and the
numbers are the same, the method returns the value true.


public classPhone
{
private intareaCode;
private intdigits;


publicPhone(int area, int number)
// Constructor
{
areaCode = area;
digits = number;
}

public intknowAreaCode()
{
returnareaCode;
}

public intknowDigits()
{
returndigits;
}
Free download pdf