Java Reference
In-Depth Information
As shown in this example, the functions and procedures are defined in the
scope of class FunctionDeclaration . These functions are called in the main
function of class FunctionDeclaration but this is not a restriction: Functions
can also be called inside the body of other functions. Observe that arguments
are expressions that may contain function calls themselves too, as in the
following example: display(square(2),distance(5,9)); . This first warm-
up example shows that functions/procedures help in writing code subroutines
and thus provide the basics for code modularity and code re-use. Code re-use
facilitates certification and correctness of programs by breaking them down
into elementary units that can be proved more easily in turn.
Since functions are encapsulated into classes, we can call any arbitrary function
F declared in another class, say OtherClass , by using the syntax OtherClass.F .
We already used this syntax when calling mathematical functions such as
Math.cos(x); that are encapsulated into the class Math . Class Math is part
of a huge set of standardized Java application programming interfaces (APIs)
that come installed with the Java development kit (JDK). We can omit the
class name when calling a function provided that the function is declared
inside the body of the same class. This is the case of all functions of our
program FunctionDeclaration . For example, display(3,2); is equivalent
to the function call FunctionDeclaration.display(3,2); . Observe that the
main function of the program class is the default procedure called upon when
executing the program.
3.2.3 A more elaborate example: The iterative factorial
function
Let us now look at how implementing the factorial function
n
n !=1
×
2
×
...
×
n =
i
i =1
+ (by convention 0! = 1)). Since the factorial function
does not belong to the basic static functions of the Math class, let us write our
own function factorial in a toolbox class named Toolbox .Weusea while
statement for accumulating the multiplications n
for any given n
N
×
...
×
1 as follows:
Program 3.3 Implementing the factorial function n !
class Toolbox
{
static int factorial( int n)
{ int result=1;
 
Search WWH ::




Custom Search