Constructor
• A constructor initializes the instance variables of an object.
• It is called immediately after the object is created but before the new operator completes.
1) it is syntactically similar to a method:
2) it has the same name as the name of its class
3) it is written without return type; the default return type of a class
• constructor is the same classWhen the class has no
constructor, the default constructor automatically initializes all its instance variables with zero.
Example: Constructor
class Box {
double width;
double height;
double depth;
Box() {
System.out.println("Constructing Box");
width = 10; height = 10; depth = 10;
}
double volume() {
return width * height * depth;
}
}
Parameterized Constructor
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
double volume()
{ return width * height * depth;
}
}