Parameters allow a method to be generalized by operating on a variety of data and/or be used in a number of slightly different situations.
Syntax
This is the general form of a method:
type methodName(parameterType variable,parameterType2 variable2,...) {
// body of method
}
Example 1
A parameterized method can operate on a variety of data.
The new Rectangle class has a new method which accepts the dimensions of a rectangle and sets the dimensions with the passed-in value.
class Rectangle {
double width;
double height;
double area() {
return width * height;
}
void setDim(double w, double h) { // Method with parameters
width = w;
height = h;
}
}
public class Main {
public static void main(String args[]) {
Rectangle mybox1 = new Rectangle();
double vol;
mybox1.setDim(10, 20);
vol = mybox1.area();
System.out.println("Area is " + vol);
}
}