Methods
Methods
appear inside class bodies. They contain local variable declarations
and other Java statements that are executed by a calling thread when
the method is invoked. Method declarations in Java look like ANSI
C-style function declarations with two restrictions: a method in Java
always specifies a return type (there’s no default). The
returned value can be a primitive type, a reference type, or the type
void, which indicates no returned value. A method
always has a fixed number of arguments. The combination of method
overloading and true arrays lessens the need for a variable number of
arguments. These techniques are type-safe and easier to use than
C’s variable-argument list mechanism.
Here’s a simple example:
class Bird {
int xPos, yPos;
double fly ( int x, int y ) {
double distance = Math.sqrt( x*x + y*y );
flap( distance );
xPos = x;
yPos = y;
return distance;
}
...
}In this example, the class Bird defines a method,
fly( ), that takes as arguments two integers:
x and y. It returns a
double type value as a result.
Local Variables
The
fly( ) method declares a local variable called
distance, which it uses to compute the distance flown. A local variable is temporary; it exists only within the scope of its method. Local variables are allocated and initialized when a method is invoked; they are normally destroyed when the method returns. They can’t be referenced from outside the method itself. If the method is executing concurrently in different threads, each thread has its ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access