JAVA CONSTRUCTORS

Java Class Constructor is a member function of a class that is called when an object is instantiated. The Java class Constructor has the same name as that of the class name, and its main function is to initialize the object with the initial values for that class.

Table of Contents

[hide]
  • What are Constructors in Java
  • Need for Constructors
  • Constructor Vs Methods in Java
  • Types of Constructors
  • Contructor Overloading in Java

What are Constructors in Java

Java Constructor is a member function of class that has the same name as that of a class, when we call the constructor the memory for the object is allocated in the memory. It is used to to initialize objects of that class type with a legal initial value.

If a class has a constructor, then every object of that class will be initialized before the object is used. If there is no constructor present in a class, then Java Compiler provides a default constructor. The constructor is just similar to methods, but with a few differences, will discuss later in the module.

Java class Constructor can not have any return type, not even void.

Example : Java Class Constructor

//Java Program to demonstrate the use of Constructor
public class Employee {
  .....

  //A Constructor
  new Employee(){
  }

  ... // other public members

  //Creates an object and call a construtor
    Employee obj = new Employee();
}

Example : Java Class (Employee) Constructor

copyimage
//Java Program to demonstrate the use of Java Class Employee Constructor
class Employee 
{ 
    int empID; 
    String empName; 
    double empSalary;
  
    // initialize object of the class type with initial values.
    Employee() { 
       System.out.println("Inside Constructor"); 
    } 
} 
  
public class Codebator 
{ 
    public static void main (String[] args) { 
        // As soon as object is created, a constructor is called.
    	Employee obj = new Employee(); 
  
        // Printing the values
        System.out.println(obj.empID); 
        System.out.println(obj.empName); 
        System.out.println(obj.empSalary); 
    } 
} 

OUTPUT :

Inside Constructor0null0.0

EXPLANATION :

The above class Employee has a member function Employee with the same as that of a class which provides initial values to the data members as shown above. As soon as we created an object of Employee type, the compiler called the constructor Employee() for newly created object.

Need for Constructors

Need of Constructor is Java is to create an instance of a class or we can say to initialize the object of a class. One the main purpose of the constructor is to provide initial values the data member, since once the object is created, memory is being allocated to the data members which cannot be empty.

Hence constructor are used to assign the initial values to the class variables at the time of object creation, either it is done by the Java compiler automatically or its done by the programmer.

In the above Employee example, we have some class variables i.e empID, empName and empSalary. When the object is created, Employee will now exists in memory which can not be empty. So we use constructor to assign values to the class variables at time of object creation.

Constructor Vs Methods in Java

Java constructor is similar to method but with some differences. Let us see some common differences between Java Constructor and Java Methods :

  • Java class constructor is used to initialize the objects of that class type with the initial values, whereas Java methods are the block that are used to perform some tasksby executing some statements.

  • Java class constructor cannot have any return type while Java methods must have a return type.

  • Java class constructor name must be same as that of a class, while Java methods may or may not be same as that of a class name.

  • A Java Compiler provides a default constructor automatically if you do not have any constructor in the class while Java method is not provided by compiler in any case.

  • A Java class constructor is called once at the time of object creation while Java methods can be called any number of times.

Types of Constructors

Java Constructor function can be of two types :

  • Default Constructor

  • Parameterized Constructor

java-constructor

Default constructors are the ones that cannot receive any parameter, also known as non-paramererized constructor or no-arg constructor, while the Parameterized constructor can receive any parameters.

Java Default Constructor

A constructor that accepts no parameter is known as default constructor, they are also considered as non-parameterized or no-args constructor.

Syntax

classname (){}

Example : Java Default Constructor

copyimage
//Java Program to demonstrate the use of Java Default Constructor
class Department { 
    // A default constructor created
    Department() { 
    System.out.println("Inside Constructor"); 
    } 
} 
public class Codebator { 
    public static void main (String[] args) { 
        // As soon as object is created, a default constructor is called.
    	Department obj = new Department(); 
    } 
} 

OUTPUT :

Inside Constructor

Example : Java Default Constructor Department

copyimage
//Java Program to demonstrate the use of Java Default Constructor
class Department { 
   int id;
   String name;

    // method to display values 
    void show() { 
    System.out.println(id +" "+ name); 
    } 
} 
public class Codebator { 
    public static void main (String[] args) { 
        // As soon as object is created, a default constructor is called.
      Department obj = new Department(); 
      Department obj1 = new Department(); 

      obj.show();
      obj1.show();
    } 
} 

OUTPUT :

0 null0 null

In the given program, we have not created any constructor, hence compiler automatically supplies a default constructor, having no arguments. Java compiler initializes the data members by any dummy value.

Java Parameterized Constructor

A Constructor that accepts any number of parameters is known as paramererized constructor. They allow us to initialize the various data elements of different objects with different values when they are created. We pass different values as arguments to the constructor function while creating the object.

Example : Java Parameterized Constructor

copyimage
//Java Program to demonstrate the use of Java Parameterized Constructor
class Department { 
   int id;
   String name;

    // parameterized constructor 
    Department(int i, String n) { 
       id=i;
       name=n;
    } 
    //method to display department values
    void show(){
       System.out.println(id +" "+ name); 
    }
} 
public class Codebator { 
    public static void main (String[] args) { 
      // passing arguments to the parameterized constructor
      Department obj = new Department(34 , "Computer Science" ); 
      Department obj1 = new Department(42 , "Electronics and Communication"); 

      obj.show();
      obj1.show();
    } 
} 

OUTPUT :

34 Computer Science42 Electronics and Communication

Declaring a constructor with arguments hides the default constructor. At the time of object creation initial values must be passed as an argument.

Contructor Overloading in Java

Java Constructor Overloading is a mechanism in which we can have more that one constructor with different parameter lists. Each Constructor performs a different tasks. Java Compiler differentiates them by the number of parameters in the list and by their types.

A Constructor can be overloaded just like a method, but does not have any return type.

copyimage
//Java Program to demonstrate the use of Java Constructor Overloading
class Department { 
   int id;
   String name;
   String student;

    // parameterized constructor with two arguments
    Department(int i, String n) { 
       id=i;
       name=n;
    } 
   // parameterized constructor with three arguments
    Department(int i, String n, String s) { 
       id=i;
       name=n;
       student=s;
    } 

    //method to display department values
    void show(){
       System.out.println(id +" "+ name +" "+student); 
    }
} 
public class Codebator { 
    public static void main (String[] args) { 
      // passing arguments to the parameterized constructor
      Department obj = new Department(34 , "Computer Science", "rajat srivastava" ); 
      Department obj1 = new Department(42 , "Electronics and Communication"); 

      obj.show();
      obj1.show();
    } 
} 

OUTPUT :

34 Computer Science rajat srivastava42 Electronics and Communication null

In the above program we can see that we have created two constructor with the same name as that of a class. The arguments to the constructor is different in both the constructor calls. Complier distinguish on the based of number of arguments provided. We have provided two args in first call and three args in second call.