Constructor in Java:
The constructor is a method. It is used to give an initial value to an instance variable of the objects. A constructor is never called directly. It is always called with a new operator.The new operator is used to create an instance of a class, it allocates a memory for the objects, initialize the data member and called the constructor method. There is two type of constructor. They are,
1.default constructor(constructor with no arguments)
2. Parameterized constructor
Default constructor:
The default constructor is a constructor with no parameters. The default constructor does nothing, but it enables all variable that is not initialized in their declaration to assume default value as follows:- Numeric data members are set too.
- Boolean data members are set to false.
-String are set to null.
The general form is,
construtorname()
{
//give initial value to data members
}
Where,
constructor name is name of the class
Parameterized constructor:
A parameter refers to a value that one adds or modify when issuing a command so that the command accomplished its task. The general format of the parameterized constructor is as follows:constructorname(datatype arg1, datatype arg2,....................)
{
//give intial value to the data members
}
where
constructor name is the name of the class
datatype arg1, datatype arg2,................... is a parameter
Rules:
- A constructor has no return type.- A constructor may take zero, one or more arguments.
- A constructor is always called with a new operator.
- A constructor has the same name as the class.
program:
class employee{
int empno;
int emp_salary;
employee()
{
empno=0;
emp_salary=0;
}
employee(int x,int y)
{
empno=x;
emp_salary=y;
}
void read(int x,int y)
{
empno=x;
emp_salary=y;
}
}
class employeedemo
{
public static void main(String args[])
{
employee e1=new employee();
employee e2=new employee(1001,20,000);
System.out,println("e1.empno:"+e1.empno);
System.out.println("e1.emp_salary:"+e1.emp_salary);
System.out,println("e2.empno:"+e2.empno);
System.out.println("e2.emp_salary:"+e2.emp_salary);
}
}
The output is:
e1.empno:0
e1.emp_salary:0
e2.empno:1001
e2.emp_salary:20,000