Week 4, Notes 1 - Methods

Purpose

A set of instructions that encapsulate a difficult aspect of the program or encapsulate an operation that is done more than once in a program.

Syntax for declaring a method

public static void methodName()  // the method ‘signature’

{

     // statements that do what the method should do

     // the method ‘body’

}

Calling a method

To execute the statements in a method, you must ‘call it’.

Insert a statement containing the method name followed by (), e.g.,

myUsefulMethod();

This statement is the method call, and the place in the code it occurs is the call site.

Control transfers to the method you named and its first instruction starts executing.

When all instructions in the method are finished, control returns to the statement following the call site.

Designing with methods

In a problem of any complexity, you can break it down into a sequence of parts.

 

Write pseudo-code at a high level, then write a method call for the first high-level item, even though this method doesn’t yet exist.

 

Finally, declare the method that will be called at runtime and write a body for it.

makeDinner example

 

Write a main program to print instructions for making dinner.  Start by writing pseudo code for the high level tasks in sequence: prepare, cook, cleanup

 

Write a method call for each task.

 

Write a method declaration each task.

 

See ../demos/W04N01.java