Constructors What Is A Constructor?
Constructors What Is A Constructor?
Constructors What Is A Constructor?
What is a constructor?
A Constructor is a member method of a class which has the same name as that of a
class with no return type. It is used to initialize the instance variable of a class with a legal
initial value and gets involved automatically as soon as the object of a class is created.
Example:
class ConsExamp
{
int n;
ConstExamp()
{
n=10;
}
Public static void main(String arg[])
{
ConsExamp c=new ConstExamp();
System.out.println(c.n);
}
}
Output:
10
In this example ConstExamp is the Class with constructor to initialize the variable n
value as 10. In the main method the value to n is initialized when the object c is created using
the Constructor. The value of n is accessed using the object name and the dot operator and
displayed.
Need of Constructor
To create an instance of a class
To initialize objects of that class type with a legal initial values.
How to Invoke a Constructor?
A constructor is created when we create the object of a class.
How an object is Created?
The object is created using the new operator.
Syntax: -
<class name> <object name> = new <constructor>
Example: -
Student s= new Student();