Mega Code Archive

 
Categories / Java Book / 002 Class
 

0141 Using Constructors

A constructor initializes an object during creation. It has the same name as the class. Constructors have no return type (not even void). The Rectangle class in the following uses a constructor to set the dimensions: class Rectangle { double width; double height; Rectangle() { width = 10; height = 10; } double area() { return width * height; } } public class Main { public static void main(String args[]) { Rectangle mybox1 = new Rectangle(); double area; area = mybox1.area(); System.out.println("Area is " + area); } } When this program is run, it generates the following results: Area is 100.0