Constructor is a special type of method that is used to
initialize the state of object.
It provides the values to the data members at the time of object
creation that is why it is known as constructor.
Characteristics of constructor
1. A constructor must have the same name as of its class.
2. It is invoked at the time of object creation and used to
initialize the state of an object.
3. It does not have an explicit return type.
Types of constructor
1. Default or no-argument constructor.
2. Parameterized constructor.
Default or no-argument constructor
A constructor with no parameter is known as default or no-argument
constructor.
If no constructor is defined in the class then compiler
automatically creates a default constructor at the time of compilation.
Syntax
Class_name()
{
//optional block of code
//optional block of code
}
Parameterized constructor
A constructor with one or more arguments is known as parameterized
constructor.
Parameterized constructor is used to provide values to the object
properties.
By use of parameterized constructor different objects can be
initialize with different states.
Syntax
class ClassName
{ .......
ClassName(list of parameters) //parameterized constructor
{ .......
}
....... }
Important points Related to Parameterized Constructor
• Whenever
we create an object using parameterized constructor, it must be define
parameterized constructor otherwise we will get compile time error.
• Whenever
we define the objects with respect to both parameterized constructor and
default constructor, It must be define both the constructors.
• In
any class maximum one default constructor but 'n' number of parameterized
constructors.
Difference between Method and Constructor
No comments:
Post a Comment