Site icon codippa

Default constructor in java

In this article, we will learn about default constructor in java, what it is, its syntax, definition with examples.

What is constructor in java

A constructor in java is a special method which has the same name as its class.
It is automatically called when we create an object of its class.
A constructor may or may not have any arguments.
A constructor that has arguments is also called parameterized constructor.

Constructor Example

Below is an example of constructor in java.

public class ConstructorDemo {
  private int id;

  public ConstructorDemo() {
  }
   
  /*
  * Parameterized constructor 
  */
  public ConstructorDemo(int id) {
    this.id = id;
  }
}

Default Constructor

In the above example, we defined two constructors inside a class.

But, even if you do not define any constructor, the compiler automatically creates one, behind the scenes.

This constructor does not accept any arguments and is created automatically.
Hence it is called Default Constructor.

Default constructor definition

Definition of default constructor as per Java Language Specification(JLS) is

If a class contains no constructor declarations, then a default constructor is implicitly declared

Default constructor syntax

A default constructor is a method that is,

  1. of the same name as its class,
  2. has the same access specifier as its class, and
  3. does not accept any arguments.

Default constructor example

Consider below class

public class DefaultTest {

}

Compile this class using java DefaultTest.java command.
This will create a new file DefaultTest.class

Now, decompile this class file with command javap DefaultTest.class and below is the output.

Compiled from "DefaultTest.java"
public class DefaultTest {
  public DefaultTest();
}

Notice that we did not define any constructor in our class but it is present in the compiled class.
This is auto generated by the compiler and is called default constructor.

Tweaks

That is all on default constructor in java.

Exit mobile version