Java Class Constructors
Description
A constructor initializes an object during object creation when using new operator.
Java allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor.
Syntax
It has the same name as the class. Constructors have no return type, not even void.
class ClassName{/*w w w.jav a2 s . co m*/
ClassName(parameter list){ // constructor
...
}
}
Example
In the following code the Rectangle
class in the following
uses a constructor to set the dimensions:
class Rectangle {
double width;/* w w w.ja v a 2s . c om*/
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: