A constructor is a member method of a class that is called for initializing when an object is created of that class. It has the same name as that of the class’s name and its primary job is to initialize the object to a legal initial value for the class.
If a class has a constructor, each object of that class will be initialized before any use is made of the object.
A simple example of a constructor –
class Student {
introllno ;
float marks ;
// constructor
public Student ( ){
rollno = 0 ;
marks = 0.0 ;
}
// other members
:
:
}
Need for Constructors –
Construtors have one purpose that is to create an instance of a class. This can also be called creating an object.
Types of Constructors –
- Parameterized
- Non-Parameterized
Non-Parameterized Constructors –
A constructor that accepts no parameter is called the non-parameterized constructor. Non-parameterized constructors are considered default constructors.
If a class has no explicit constructor defined, the compiler will supply a default constructor.
When a user-defined class does not contain an explicit constructor, the compiler automatically supplies a default constructor, having no arguments.
For example,
public class A {
int i ;
voidgetval () { . . . . }
voidprnval () { . . . . }
// member methods definitions
}
class B {
void test ()
{
A ol = new A () ; // compiler automatically provided constructor for class A
ol.getval () ;
ol.prnval () ;
}
}
Parameterized Constructor –
A constructor with arguments is called a parameterized constructor. The parameterized constructors allow us to initialize the various data elements of different objects with different values when they are created. This is achieved by passing different values as arguments to the constructor method when the objects are created.
Following definitions shows a parameterized constructor:
class ABC {
int i ;
float j ;
char k ;
public ABC (int a, float b, char c) { // parameterized constructor
i = a ;
j = b ;
k = c ;
}
:
: // other members
}
- A simple program for Constructor
Program
/* Here, Box uses a constructor to initialize the dimensions of a box.*/
classBox {
double width ;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println(“Constructing Box”);
width= 10;
height= 10;
depth= 10;
}
//compute and return volume
double volume() {
return width * height * depth;
}
}
classBoxDemo {
public static void main (String args []) {
//declare, allocate, and initialize Box objects
Box mybox1= new Box();
Box mybox2= new Box();
doublevol;
// get volume of first box
vol = mybox1.volume ();
System.out.println(“ Volume is “+ vol);
//get volume of second box
vol = mybox2.volume();
System.out.println(“Volume is”+ vol);
}
}
Output
When this program is run, it generates the following result:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0