Mega Code Archive

 
Categories / Java Book / 002 Class
 

0142 Constructors with Parameters

The constructors can also have parameters. Usually the parameters are used to set the initial states of the object. 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); } } The output from this program is shown here: Area is 200.0