Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^294) | Object-Oriented Software Design and Implementation
public longasDigits()
// Returns area code and number as a sequence of 10 digits
{
return(long)(areaCode * 10000000L+ digits);
}
publicString asString()
// Returns area code, hyphen, first three digits of the number, hyphen,
// and last four digits of the number
{
String result;
longfirstThree; // First three digits of the number
longlastFour; // Last four digits of the number
firstThree = digits / 10000 ;
lastFour = digits % 10000 ;
result = new String(areaCode + "-" + firstThree + "-" + lastFour);
returnresult;
}
public booleanequals(Phone secondNumber)
// Returns true if the phone numbers are the same; false otherwise
{
if (areaCode != secondNumber.knowAreaCode())
return false;
if (digits != secondNumber.knowDigits())
return false;
else
return true;
}
}


6.7 Packages


As we noted previously, Java lets us group related classes together into a unit called a pack-
age. Classes within a package can access each other’s nonprivate members, which can save
us programming effort and make it more efficient to access their data. The other advantage
of packages is that they can be compiled separately and imported into our code. Together with
the access modifiers, packages provide the means for implementing encapsulation because
they allow us to distribute our classes as Bytecode files. The unreadable nature of Bytecode
prevents users from seeing the implementation details.

Package Syntax


The syntax for a package is extremely simple. We’ve been writing our separate classes as un-
named packages all along, so we merely have to specify the package name at the start of the
class. The first line of a package consists of the keyword packagefollowed by an identifier and
Free download pdf