What is the purpose of a default constructor in Java?


Default constructors in Java:

A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type. There are two types of constructors namely −

  • parameterized constructors − Constructors with arguments.
  • no-arg constructors − Constructors without arguments.

Example

 Live Demo

public class Sample{
   int num;
   Sample(){
      num = 100;
   }
   Sample(int num){
      this.num = num;
   }
   public static void main(String args[]){
      System.out.println(new Sample().num);
      System.out.println(new Sample(1000).num);
   }
}

Output

100
1000

Default Constructor

It is recommended to provide any of the above-mentioned contractors while defining a class. If not Java compiler provides a no-argument, default constructor on your behalf.

This is a constructor initializes the variables of the class with their respective default values (i.e. null for objects, 0.0 for float and double, false for boolean, 0 for byte, short, int and, long).

If you observe the following example, we are not providing any constructor to it.

public class Sample{
   int num;
   public static void main(String args[]){
      System.out.println(new Sample().num);
   }
}

If you compile and run the above program the default constructor initializes the integer variable num with 0 and, you will get 0 as result.

Verifying with javap

The javap command displays information about the fields, constructors, and methods of a class. If you (after compiling it) run the above class using javap command, you can observe the default constructor added by the compiler as shown below:

D:\>javap Sample
Compiled from "Sample.java"
public class Sample {
   int num;
   public Sample();
   public static void main(java.lang.String[]);
}

Updated on: 12-Mar-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements