Constructor is a special method that creates and return an object of the class in which they are defined. Constructor has the same name as that of class and has no return type not even void.
There are three types of constructor in Java-
This constructor takes no argument and is called when an object is created without any explicit initialization.
Note- The compiler provides default constructor when you do not write any constructor for a class. If you provide at least one constructor for the class, then the compiler does not provide any constructor.
public class Car { public Car() { System.out.println("Car is created."); } public static void main(String args[]) { Car c = new Car(); } }
Output
Car is created.
This constructor is called when an object is created and it is initialized with some values at the time of creation.
public class Employee { int id; String name; public Employee(int i, String n) { id = i; name = n; } void show() { System.out.println(id+" "+name); } public static void main(String args[]) { Employee emp1 = new Employee(1, "Govind"); Employee emp2 = new Employee(2, "Akash"); emp1.show(); emp2.show(); } }
Output
1 Govind 2 Akash
This constructor is called when an object is created and it is initialized with some other object of the same class at the time of creation.
public class Employee { int id; String name; public Employee(int i, String n) { id = i; name = n; } public Employee(Employee e) { id = e.id; name = e.name; } void show() { System.out.println(id+" "+name); } public static void main(String args[]) { Employee emp1 = new Employee(1, "Govind"); Employee emp2 = new Employee(emp1); emp1.show(); emp2.show(); } }
Output
1 Govind 1 Govind
public class Employee { int id; String name; int salary; public Employee(int i, String n) { id=i; name=n; salary=0; } public Employee(int i, String n, int s) { id=i; name=n; salary=s; } void show() { System.out.println(id+" "+name+" "+salary); } public static void main(String args[]) { Employee emp1 = new Employee(1, "Govind"); Employee emp2 = new Employee(2, "Akash", 10000); emp1.show(); emp2.show(); } }
Output
1 Govind 0 2 Akash 10000
There are two rules for calling a constructor-
Constructor | Method |
---|---|
Constructor is used to initialize the memory and member of the object. | Method is used to define behaviour of an object. |
Constructor does not have any return type not even void. | A method must have a return type. |
A contructor cannot be declared static. | Writing static method is valid. |
You cannot apply final keyword to a constructor. | A method can be made final to prevent overriding. |
You are not allowed to apply abstract keyword to a constructor. | A method can be declared abstract. |