Method with Parameters
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);
}
}
The output:
Area is 200.0
Using Objects as Parameters
The following code passes objects to methods.
class Test {
int a;
Test(int i) {
a = i;
}
boolean equals(Test o) {
if (o.a == a )
return true;
else
return false;
}
}
public class Main {
public static void main(String args[]) {
Test ob1 = new Test(100);
Test ob2 = new Test(100);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
}
}
This program generates the following output:
ob1 == ob2: true