- A constructor is a special method which is used to initialize the object at the time of the creation
- Java allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of constructor.
- The constructor is called automatically when an object is created.
- It has the same name as the class name.
- Constructor does not have any return type not even void
- Most classes explicitly define their own constructors within their class definition.
- Default constructor will be supply automatically if no explicit constructor is specified.
- The Box class contains two constructors, one is the default constructors and other is the parameterized constructor that accepts parameter to initialize
- Default constructor will be called for mybox1 while parameterized constructor will be called for mybox2
class Box
{
double width, height, depth;
Box()
{
Height=width=depth=0;
}
Box (double h,doublew,double d)
{
Height = h;
width = w;
depth = d;
}
double volume()
{
return width*height*depth;
}
}
classBoxDemo
{
public static void main (String args[])
{
doublevol;
Box mybox1 = new Box ();
Box mybox2 = new Box (10,20,30);
vol = mybox1.volume ();
System.out.println (“Volume is: -“+vol);
vol = mybox2.volume ();
System.out.println (“Volume is: -“+vol);
}
}