Constructor in Java

  • A special type of method that is used to initialize the object, is known as constructor.
  • Both the constructor and class name must be same.
  • They are invoked automatically when an object creates.
  • Java compiler creates a default constructor for a class when any explicit constructor of that class is not declared.

Types of Constructor

Java provides two types of constructors:
1. Default constructor
2. Parameterized constructor

Default constructor

Default constructor is also known as no-args constructor because it has no parameter.

Example: Sample program for default constructor

class DefaultCon
{
     int length = 25;
     int width = 20;
     DefaultCon()
     {
          System.out.println("Area of rectangle: "+(length*width));
     }
     public static void main(String args[])
     {
          DefaultCon emp = new DefaultCon();
     }
}


Output: Area of rectangle: 500

Parameterized Constructor

A constructor that contains argument list is known as parameterized constructor.

Example: Sample program for parameterized Constructor

class Rectangle
{
     int length;
     int width;
     Rectangle (int a, int b)
     {
          length = a ;
          width = b ;
     }
     int calculateArea()
     {
          return(length*width);
     }
     public static void main(String args[])
     {
          Rectangle rec = new Rectangle (25, 15);
          long area = rec.calculateArea();
          System.out.println("Area of Rectangle: "+area);
     }
}


Output:
Area of Rectangle: 375

Constructor Overloading

Constructor overloading means declaring multiple constructors with different parameter in the similar class.

Example: Sample program for constructor Overloading

class Employee
{
     String name;
     int age;
     String company;
     Employee (String a, int b)
     {
          name = a ;
          age = b ;
     }
     Employee (String a, int b, String c)
     {
          name = a ;
          age = b ;
          company = c;
     }
     Employee (String a, String b)
     {
          name = a ;
          company = b ;
     }
     void display()
    {
          System.out.println(name+"  "+age+"  "+company);
     }
     public static void main(String args[])
     {  
          System.out.println("Name Age Company");
          Employee emp1 = new Employee("ABC", 23);
          Employee emp2 = new Employee("XYZ",30,"TutorialRide.com");
          Employee emp3 = new Employee("PQR", "CareerRide Info");
          emp1.display();
          emp2.display();
          emp3.display();
     }
}


Output:
Name  Age  Company
ABC  23  null
XYZ  30  TutorialRide.com
PQR  0  CareerRide Info