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{
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;
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);
}
}