Chapter 6 Methods

Every method must be contained within a class.

Two Types: static and non-static

A static method is to receive all of its data as arguments and can access or modify any variable that is shared by all objects of the class. A static method can be used without referring to a specific object constructed from a class. They can appear before or after main because they are static.

public can be used by methods outside of its own class.

(later we will use protected and private).

Static methods are general-purpose methods that are not restricted to operate on objects of a specific class.

We will learn: 1. to pass data to them

2. process passed data

3. return a result

(non-static in Chapter 9)

The first line of the method is called the method’s signature.

Arguments to the methods are passed by value. Primitives will remain unchanged; however, references will not because a copy of the address

used by the method but that address still points to the same object as the calling method.

Methods cannot be nested – must be written by itself outside of any other method.

Classes can be nested within classes and can even be contained within a method.

It is good programming style to follow the following placement of statements in a method:

1.  named constants

2.  variable declarations

3.  other statements

4.  return value

Top Down Design: breaking down a task into smaller subtasks. This process is continued until the original task is broken down into units that each describe a specific goal. Using methods to define tasks is called procedural abstraction.

Use method stubs to achieve top down design.

A stub is the beginning of a method that can be used as a placeholder until the details of the methods are completed at a later time.

Look at program on p. 229 and stub on p. 230.

Method Overloading

is the capability of using the same method name for more than one method.

The compiler must be able to determine which method to use based on the data types of the parameters (not the data type of the return value, if any).

Take, for example, the following method signatures:

public static void calcabs (int x)

public static void calcabs (float x)

public static void calcabs (double x)

The method called depends on the argument type supplied at the time of the call.

Part of the method signature or method header line that contains the name and parameter list is called method parameter signature.

Methods must have a unique method parameter signature.

On the board: Pi method p233 #12