Constructor in Java.
Constructor
1.It is a special member function of class that executes when we create the instance(object) of that class.in other word we can say that there is no need to call a constructor.
2.Its name is same as class name.
3.It has no return type.
4.It may be parameterized or non-parameterized.
5.It is used to initialize class level variable.
Example
class Rectangle
{
//Data Member
int height;
int width;
int area;
//constructor
//notice here there is no return type and name is same as class name
Rectangle()
{
height=15;
width=25;
area=height*width;
System.out.println("Area of Rectangle="+area);
}
public static void main(String[] args)
{
//creating object
//notice here no need to call a constructor
Rectangle obj=new Rectangle();
}
}
/*
### Output ###
Area of Rectangle=375
*/
Types of constructor
There are three types of constructor.
- Default Constructor.
- Parameterized Constructor.
- Copy Constructor.
Default Constructor
The constructor with no parameter is called default constructor.
class Rectangle
{
//Data Member
int height;
int width;
int area;
//constructor
//notice here there is no return type and name is same as class name
Rectangle()
{
height=15;
width=25;
area=height*width;
System.out.println("Area of Rectangle="+area);
}
public static void main(String[] args)
{
//creating object
//notice here no need to call a constructor
Rectangle obj=new Rectangle();
}
}
/*
### Output ###
Area of Rectangle=375
*/
Parameterized Constructor
The constructor with parameter is called Parameterized constructor.
class Rectangle
{
//Data Member
int area;
//constructor
//notice here there is no return type and name is same as class name
Rectangle(int height,int width)
{
area=height*width;
System.out.println("Area of Rectangle="+area);
}
public static void main(String[] args)
{
//creating instance(object) of class
/*notice here there are two value is passed
because there are two parameter in constructor
15 will assign to height and 25 will assign to width
*/
Rectangle obj=new Rectangle(15,25);
}
}
/*
### Output ###
Area of Rectangle=375
*/
Copy Constructor
In this type of constructor one object with parameter is copied into another object so it is called copy constructor.
class Rectangle
{
//Data Member
int area;
//constructor
//notice here there is no return type and name is same as class name
Rectangle(int height,int width)
{
area=height*width;
}
void show()
{
System.out.println("Area of Rectangle="+area);
}
public static void main(String[] args)
{
//creating instance(object) of class
/*notice here there are two value is passed
because there are two parameter in constructor
15 will assign to height and 25 will assign to width
*/
Rectangle obj1=new Rectangle(15,25);
obj1.show();
//passing obj1 in obj2
Rectangle obj2=obj1;
obj2.show();
}
}
/*
### Output ###
Area of Rectangle=375
Area of Rectangle=375
*/
Destructor
1.There is no destructor in JAVA.