Other languages use: subroutine, sub, function, procedure...
A method is a section of code with a name, eg:
private void myTask(){
x=4;
y=5;
}
To call it up (invoke it) - we put:
myTask();
private - the method can only be used within its class
void - the method does not use 'return' to pass data back to the
caller
Passing parameters to the method
All programming languages have parameter-passing - v.important!
Example: A method which adds any two integers together, and leaves
the result in sum. We declare it:
private void addUp(int a, int b) { sum=a+b; }
a and b are termed the 'formal parameters'
Here are some invocations/calls:
int d=7, e=3; addUp(5,6); addUp(d,4); addUp(d+e, 1);
Note:
when we invoke a method, we provide 'actual parameters'
they must be the right type (int here)
they must be the same number of them (2 here)
they match up left to right with the formal parameters
the current values are copied into the formal names (e.g. 5 into a,
6 into b)
the values of the actual parameters are used inside the method
what values does sum take, above?
The layout of a class
class Fred.... {
private int sum, n = 0; // 'instance variables' -global to all methods of class
public aMethod(){
int n=3;
addUp(n,6);
}
private void addUp(int a, int b) {
sum=a+b;
}
}
private - can only be used from within the class
public - can be used from other classes
Scopes
Where names clash, local variables and formal parameters take
precedence, e.g:
in aMethod, n is 3 (the global n still
exists, as 0)