Programming and Problem Solving with Java

(やまだぃちぅ) #1
3.7 Value-Returning Class Methods | 123

a publicclass method that has no parameters and returns an intresult. We would write the
heading this way:


public static intmyMethod()


The only difference between this heading and the ones we wrote in Chapter 2 is the use of
the reserved word static. We follow the heading with the body of the method enclosed in
braces, just as we did for instance methods. Within the body, when our computation is fin-
ished, we write a returnstatement.
Let’s look at an example of a value-returning class method declaration. The method
should return a random integer in the range of 1 to 10. We call the Math.randommethod, which
returns a value that is greater than or equal to 0.0 and less than 1.0. We must change this value
into our desired range, so we multiply it by 10.0 and convert the result to an int. The intwill
then be in the range of 0 to 9, so we add 1 to get a number in the desired range. Here’s the
expression that does the job:


(int) (Math.random() * 10.0) + 1


Now we’re ready to write the method. Let’s call it random1to10.


public static intrandom1to10()
{
return(int) (Math.random() * 10.0) + 1;
}


Is that it? Our new method is just like the value-returning methods that we wrote in
Chapter 2, except that the heading includes static. Of course, we call it by using the name
of the class in which we declare it rather than an object name. It also bears repeating that
class methods can access class fields, but not instance fields. Many value-retuning methods
are self-contained, as in the case of the preceding example. That is, they don’t need to ac-
cess any fields. As a consequence, they can be either class methods or instance methods.
However, the advantage of a class method is that we can use it even when we haven’t in-
stantiated any objects of the class. For example, we don’t have to instantiate an object of the
class Mathto be able to use its class methods. Instance methods must be used in conjunction
with an object, so we have to instantiate the class to make use of them.
As noted in Chapter 2, we will defer looking closely at the parameter list syntax until later.
But from what we’ve already said about writing parameters, you could easily extend this ap-
proach to write a method that takes numeric arguments. For example, suppose you want a
method that computes the hypotenuse of a right triangle from its other two sides. You could
write the following:


public static doublehypotenuse(doubleside1, doubleside2)
{
returnMath.sqrt(side1 side1 + side2 side2);
}

Free download pdf