Programming and Problem Solving with Java

(やまだぃちぅ) #1
2.4 Classes and Methods | 81

To call a class method, we append its name to the class identifier instead of an object
identifier. We can use a class method to specify properties that are common to all objects.
For example, in a Dateclass, where we can format a date for output in multiple ways, we might
have a method that specifies the format to use for all date objects:


Date.setDefaultFormat(Date.MONTH_DAY_YEAR);


You may have noticed that the argument in this call is a constant that is also appended to
the class name. This argument exemplifies the use of a class field. The Dateclass provides
us with constants representing the different date formats that we can use as arguments to
its methods.


Helper Methods Helper methods are declared privately within a class. They are used in complex


classes to help organize the code or to provide operations that are used only internally to the class.
Thus helper methods are called from within other methods of the class. A call to a helper method
is not appended to an object or class identifier because it is clear which class it is in, and it is not
associated with any specific object. We won’t use helper methods until much later in this book.


Constructors We use essentially the same syntax for a constructor as for any other method,


but with two special differences: (1) the method name is identical to the class name and (2)
there is no voidkeyword. Constructors are almost always declared as public; a private con-
structor would be nearly useless because it could be called only from within the class. Here
is an example constructor heading for a class called Name:


publicName(String firstName, String lastName, String middleInit)


Value-Returning Methods All of the method headings we’ve examined so far have been for void


methods or constructors. Java also supports value-returning methods. Let’s see how they dif-
fer from void methods.
Value-returning methods are called from within expressions and can be instance meth-
ods, class methods, or helper methods. Constructors are neither void methods nor value-re-
turning methods; they are a special case that is separate from the other kinds of methods.
The same rules apply for writing a method call, whether it is void or value-returning. The
only difference relates to where the call appears (in an expression or as a separate statement).
For an instance method, we append the method name to the object name with a dot in be-
tween. For a class method, we append the method name to the class name with a dot sep-
arating them. We call a helper method simply by using its name. Here are example calls:


nameString = myName.firstLast(); // Instance call; myName in an object
formatString = Name.getFormat(); // Class call; Name is the class name
initialchar = getInitial(middle); // Helper call; used inside of Name class only

Free download pdf