What is Constructor ? Explain different types of Constructor
Constructor is a member function having the same name as of its class an is executed automatically when the object is created.
Example :- class Box {
double width;
double height;
double depth;
//This is the constructor for Box
Box() {
System.out.println(“Constructing Box”);
width = 10;
height = 10;
depth = 10;
}
//computer and return volumn
double volume() {
return width*height*depth;
}
}
Class BoxDemo6 {
Public static void main(String args[]) {
//declare, allocation, and initialize Box objects
Box mybox1 = new Box() ;
Box mybox2 = new Box();
double vol;
//get volume of first box
vol = mybox1.volume() ;
System.out.println(“Volume is”+vol);
//get volume of first box
vol = mybox2.volume() ;
System.out.println(“Volume is”+vol);
}
}
There are three types of constructor :-
1. Parameterized constructor.
2. Multiple constructor.
3. Copy constructor.
No comments :
Post a Comment