JAVA.
Constructor is an important topic to write a java program. So, what is constructor?
and what are the types of constructor? keep your mind concentrated and read the following completely to get the answer.
CONSTRUCTOR.
A constructor is a member function(method/behavior) with a name same as a class name and it is automatically called when the object is created.
Usually constructor is used to initialize the instants variables of the object.
The general form of constructor is:
class classname()
{
//data member
classname()
{
//initialize data member
}
}
Features of constructor.
- A constructor is a member function with a name same as a class name and it is automatically called when the object is created.
- Construction is an argument.
- We can have any number of constructors provided they take different number or types of argument.
- Constructor do not specify any return type or even void, because they return the instance of class itself.
- Constructor is used for initializing the data member or for memory allocation, but allows any types of statement.
Types of constructor.
There are 3 types of constructor.
- Default constructor.
- A parameterized constructor.
- Copy constructor.
Default Constructor.
Default constructor is a member function with same name as the class name that takes no arguments.
When an object is created without any argument this default constructor is called.
It is best used for initialization of data members.
Parameterized constructor.
Parameterized constructor is a member function with same name as the class name that takes arguments.
It is used to initialize the data member by passing parametric value at the time of its creation.
If there is more then one construction of this types, the constructors are called depending on the number of arguments supplied.
Copy constructor.
Copy constructor is a member function with same name as the class name that takes the object of same class as argument.
It is useful when all properties of an object has ti be assigned to another object.
Bonus:
Constructor overloading.
A process to use a number of constructor with the same names but different types of parameter list is known as constructor overloading.
It is used when objects are required to perform similar tasks but using different input parameters.
check out: Classes.
Comments
Post a Comment