A constructor in Java is a block of code similar to a method that’s called when an instance of an object is created. A constructor doesn’t have a return type. The name of the constructor must be the same as the name of the class. A constructor is called automatically when a new instance of an object is created.
Types of java constructors:
There are two types of constructors in java: 1. Default constructor (no-arg constructor) 2. Parameterized constructor
1)Default Constructor:
A constructor having no parameter is known as default constructor and no-arg constructor.
public class DC { public DC(){ System.out.println(” default constructor…”); } public static void main(String a[]){ DC mdc = new DC(); }}
2)parameterized constructor:
A constructor having an argument list is known as a parameterized constructor. Parameterized constructors are used to supply dissimilar values to the distinct objects.
public class PC{ PC(int a, int b){ System.out.println(“Parameterized Constructor having 2 parameters”); System.out.println(a+b);
} PC(int a, int b, int c){ System.out.println(“Parameterized Constructor having Three parameters”); System.out.println(a+b+c); } public static void main(String args[]){ PC pc1 = new PC(12, 12); PC pc2 = new PC(1, 2, 13); }}
Constructor Overloading:
Constructor overloading is a concept of having more than one constructor with different parameters list, in such a way so that each constructor performs a different task.
public class Employee{ int id; String name; int age; Employee(int i,String n){ id = i; name = n; } Employee(int i,String n,int a){ id = i; name = n; age=a; } void display() {
System.out.println(id+” “+name+” “+age); } public static void main(String args[]){ Employee s1 = new Employee(256,”James”); Employee s2 = new Employee(257,”Gosling”,25); s1.display(); s2.display(); } }