What is the purpose of a constructor in java?

Java 8Object Oriented ProgrammingProgramming

A constructor in Java is syntactically similar to methods. The difference is that the name of the constructor is same as the class name and it has no return type. You need not call a constructor it is invoked implicitly at the time of instantiation.

The main purpose of a constructor is to initialize the instance variables of a class. There are two types of constructors −

  • Parameterized constructor − This accepts parameters. usually, using this you can initialize the instance variables dynamically with the values specified at the time of instantiation.
public class Sample{
   Int i;
   public sample(int i){
      this.i = i;
   }
}
  • Default constructor − This does not accept any parameters. Usually, using this you can initialize the instance variables with fixed values.
public class Sample{
   Int i;
   public sample(){
      this.i = 20;
   }
}

If you do not provide any constructor the Java compiles writes one (default constructor) on behalf of you, and initializes the instance variables with default values such as, 0 for integer, null for String, 0.0 for float etc…

Example

In the following example the Student class has two private variables age and, name. In this, a parameterized and a default constructor.

From main method we are instantiating the class using both constructors −

import java.util.Scanner;
public class StudentData {
   private String name;
   private int age;
   //parameterized constructor
   public StudentData(String name, int age){
      this.name =name;
      this.age = age;
   }
   //Default constructor
   public StudentData(){
      this.name = "Krishna";
      this.age = 20;
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      //Reading values from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the name of the student: ");
      String name = sc.nextLine();
      System.out.println("Enter the age of the student: ");
      int age = sc.nextInt();
      System.out.println(" ");
      //Calling the parameterized constructor
      System.out.println("Display method of parameterized constructor: ");
      new StudentData(name, age).display();
      //Calling the default constructor
      System.out.println("Display method of default constructor: ");
      new StudentData().display();
   }
}

Output

Enter the name of the student:
Raju
Enter the age of the student:
19
Display method of parameterized constructor:
Name of the Student: Raju
Age of the Student: 19
Display method of default constructor:
Name of the Student: Krishna
Age of the Student: 20
raja
Published on 03-Jul-2019 16:50:41
Advertisements