(^132) | Arithmetic Expressions
following three files in a single application directory. The ellipsis (... ) between the braces in-
dicates the code for the class.
className { ... }
classAddress { ... }
public classMailList { ... } // Imports Name and Address
The application classMailListthen has access to the other two classes, and all these
classes have access to one another’s nonprivate members.Two of the classes,NameandAddress,
are notpublic, so they are not visible to the JVM. However, they are also notprivate. Recall that
we usepublicto make a class visible outside of itself, and that the JVM is outside of an appli-
cation. Classes in the same directory are considered to be like a family, so that they can access
one another’s nonprivate members without beingpublic. Later, when we explore Java’s pack-
age construct in more detail, we will see that this kind of access is called package access. If we
make these classesprivate, then they will have access only to one another’spublicmembers.
As an example, let’s see how we can turn the Nameclass from the application in Chapter
2 into a class that we could import into an application. At the same time, let’s enhance the
class to make it more general. In its original form, it has just one constructor that goes to the
screen to get the parts of a name. We’ll add a constructor that accepts the three strings as
arguments. The constructor then assigns the values of its arguments to the corresponding
fields in the class. It’s such a simple method that we can code it directly:
publicName(String firstName, String lastName, String middleName)
{
first = firstName; // Assign parameters to fields
last = lastName;
middle = middleName;
}
Let’s also add a method that returns the full name in the usual format of first, then mid-
dle, then last name. This method is equally simple, as it just returns the concatenation of the
three strings:
publicString full()
{
returnfirst + " " + middle + " " + last;
}
All we have to do besides adding these methods is to place the class code in a separate
file called Name.javawithin the directory that has the application, and omit access modi-
fiers from the class heading. Here is the Nameclass, with the new methods:
やまだぃちぅ
(やまだぃちぅ)
#1