Java Reference
In-Depth Information
boss
worker1
worker2
worker3
worker4
worker5
Fig. 6.1 | Hierarchical boss-method/worker-method relationship.
6.3 static Methods, static Fields and Class Math
Although most methods execute in response to method calls on specific objects , this is not
always the case. Sometimes a method performs a task that does not depend on an object.
Such a method applies to the class in which it's declared as a whole and is known as a stat-
ic method or a class method .
It's common for classes to contain convenient static methods to perform common
tasks. For example, recall that we used static method pow of class Math to raise a value to
a power in Fig. 5.6. To declare a method as static , place the keyword static before the
return type in the method's declaration. For any class imported into your program, you
can call the class's static methods by specifying the name of the class in which the
method is declared, followed by a dot ( . ) and the method name, as in
ClassName . methodName ( arguments )
Math Class Methods
We use various Math class methods here to present the concept of static methods. Class
Math provides a collection of methods that enable you to perform common mathematical
calculations. For example, you can calculate the square root of 900.0 with the static
method call
Math.sqrt( 900.0 )
This expression evaluates to 30.0 . Method sqrt takes an argument of type double and re-
turns a result of type double . To output the value of the preceding method call in the com-
mand window, you might write the statement
System.out.println(Math.sqrt( 900.0 ));
In this statement, the value that sqrt returns becomes the argument to method println .
There was no need to create a Math object before calling method sqrt . Also all Math class
methods are static —therefore, each is called by preceding its name with the class name
Math and the dot ( . ) separator.
Software Engineering Observation 6.4
Class Math is part of the java.lang package, which is implicitly imported by the compiler,
so it's not necessary to import class Math to use its methods.
 
 
Search WWH ::




Custom Search