What are the differences between default constructor and parameterized constructor in Java?

JavaObject Oriented ProgrammingProgramming

Default Constructor

  • A default constructor is a 0 argument constructor which contains a no-argument call to the super class constructor.
  • To assign default values to the newly created objects is the main responsibility of default constructor.
  • Compiler writes a default constructor in the code only if the program does not write any constructor in the class.
  • The access modifier of default constructor is always the same as a class modifier but this rule is applicable only for “public” and “default” modifiers.

When will compiler add a default constructor

  • The compiler adds a default constructor to the code only when the programmer writes no constructor in the code.
  • If the programmer writes any constructor in the code, then the compiler doesn't add any constructor.
  • Every default constructor is a 0 argument constructor but every 0 argument constructor is not a default constructor.

Parameterized Constructors

  • The parameterized constructors are the constructors having a specific number of arguments to be passed.
  • The purpose of a parameterized constructor is to assign user-wanted specific values to the instance variables of different objects.
  • A parameterized constructor is written explicitly by a programmer.
  • The access modifier of default constructor is always the same as a class modifier but this rule is applicable only for “public” and “default” modifiers.

Example

Live Demo

public class Student {
   int roll_no;
   String stu_name;
   Student(int i, String n) { // Parameterized constructor
      roll_no = i;
      stu_name = n;
   }
   void display() {
      System.out.println(roll_no+" "+stu_name);
   }
   public static void main(String args[]) {
      Student s1 = new Student(1,"Adithya");
      Student s2 = new Student(2,"Jai");
      s1.display();
      s2.display();
   }
}

In the above program, the programmer defines one parameterized constructor with 2 parameters. Now the compiler adds no default constructor to the code, and nor the programmer has written any 0 argument constructor.

Output

1 Adithya
2 Jai
raja
Published on 10-Jun-2019 17:37:02
Advertisements