Explain Constructor In Java
"The constructor is a special method whose task initialize the data members of a class".
→ Class name and constructor name must be same.
→ It's a special kind of method.
→ They don't have return type not even void.
→ Constructor call automatically when an object is created.
→ They can't be inherited, through a derived class can call the base class constructor.
Syntax:
public class_name(args)
{
//Statement;
}
There is 2 type of constructor available in java.
1) Default constructor
2) Parameterized constructor
#1) Default constructor
If you do not implement any constructor in your class, Java compiler inserts a default constructor into your code on your behalf. This constructor is known as default constructor.
Class A
{
int a;
public A()
{
a=10;
}
}
class demo
{
public static void main(String args[])
{
A obj=new A();
}
}
#2) Parameterized constructor
Constructor with arguments(or you can say parameters) is known as Parameterized constructor.
public class Employee
{
int empId;
String empName;
Employee(int id, String name)
int empId;
String empName;
Employee(int id, String name)
{
this.empId = id;
this.empName = name;
}
void info()
this.empId = id;
this.empName = name;
}
void info()
{
System.out.println("Id: "+empId+" Name: "+empName);
}
System.out.println("Id: "+empId+" Name: "+empName);
}
public static void main(String args[])
{
Employee obj1 = new Employee(10245,"Chintan");
Employee obj2 = new Employee(92232,"Nigam");
obj1.info();
obj2.info();
}
}
Employee obj1 = new Employee(10245,"Chintan");
Employee obj2 = new Employee(92232,"Nigam");
obj1.info();
obj2.info();
}
}