Java Reference
In-Depth Information
Self-Test Exercises
1. Write a method called makeItNewYears that could be added to the class
DateFirstTry in Display 4.1 . The method makeItNewYears has no parameters
and sets the month instance variable to "January" and the day instance variable
to 1 . It does not change the year instance variable.
2. Write a method called yellIfNewYear that could be added to the class
DateFirstTry in Display 4.1 . The method yellIfNewYear has no parameters
and outputs the string "Hurrah!" provided the month instance variable has the
value "January" and the day instance variable has the value 1 . Otherwise, it
outputs the string "Not New Year's Day."
More about Methods
As we noted for predefined methods, methods of the classes you define are of two kinds:
methods that return (compute) some value and methods that perform an action other
than returning a value. For example, the method println of the object System.out is
an example of a method that performs an action other than returning a value; in this
case, the action is to write something to the screen. The method nextInt of the class
Scanner , introduced in Chapter 2, is a method that returns a value; in this case, the
value returned is a number typed in by the user. A method that performs some action
other than returning a value is called a void method. This same distinction between
void methods and methods that return a value applies to methods in the classes you
define. The two kinds of methods require slight differences in how they are defined.
Both kinds of methods have a method heading and a method body, which are
similar but not identical for the two kinds of methods. The method heading for a void
method is of the form
public void Method_Name(Parameter_List)
The method heading for a method that returns a value is
public Type_Returned Method_Name (Parameter_List)
Later in the chapter, we will see that public may sometimes be replaced by a
more restricted modifier and that it is possible to add additional modifiers, but these
templates will do right now. For now, our examples will have an empty Parameter_List .
If a method returns a value, then it can return different values in different situations,
but all values returned must be of the same type, which is specified as the type returned.
For example, if a method has the heading
public double myMethod()
 
Search WWH ::




Custom Search