How to pass in value with parameters for constructors?
The constructors can also have parameters. Usually the parameters are used to set the initial states of the object.
Syntax
Syntax for Java Constructor Parameters
class ClassName{
ClassName(parameterType variable,parameterType2 variable2,...){ // constructor
...
}
}
Example
In the the following demo code Rectangle class uses the parameters, w for width and h for height, from the constructors to initialize its width and height.
class Rectangle {
double width;
double height;
Rectangle(double w, double h) {
width = w;
height = h;
}
double area() {
return width * height;
}
}
public class Main {
public static void main(String args[]) {
Rectangle mybox1 = new Rectangle(10, 20);
double area;
area = mybox1.area();
System.out.println("Area is " + area);
}
}