An object is constructed using constructor. It called constructor because it constructs the values of data member of the class automatically.
The constructor is a special method for initialization of an object automatically. Whenever an object is created, the constructor is called to initialize the instance variable.
The constructor is always given the same name as the class. The constructor is automatically called immediately after the object is created ,before the new operator completes. It has no return type not even void. It can be declare as follow
class ClassName
{
[variable declaration]
Classname(Parameter list)
{
// Body of constructor.
}
[method declaration]
}
As shown in above format the constructor can be declared as the same name as class name without any return type.
A constructor may have different types: such as constructors have no arguments, with arguments. A class may have more than one constructor.
Ex,.
class Data
{
int no1,no2;
Data()
{
no1=10;
no2=20;
}
}
Here, the Data is the constructor with no parameter.
It can also having list of parameters. It is known as parameterized constructor.
For ex,
class Data
{
int no1,no2;
Data(int n1,int n2)
{
no1=n1;
no2=n2;
}
}
constructor can be invoked as .
Data obj1=new Data();
Data obj1=new Data(100,200);
Note : When no constructor is defined for a class , then the compiler supplies the default constructor. It automatically initializes all the instance variables to zero.
Ex,
A obj=new A();
Constructors are similar to methods, but with some important differences.
| ||||||||||||||||||||||||||||||||
Posted by : Ruchita Pandya | ||||||||||||||||||||||||||||||||
No comments:
Post a Comment