Default constructor in Java Tutorial

In this section, we will learn what the default constructor is and how to use it in Java.

Note: We’re also assuming that you’re familiar with the Java constructors.

What is default constructor in Java?

By default, if we explicitly don’t create a constructor in Java, the compiler will assign one to it and that is called the default constructor.

This constructor does not have any parameter, and its body is also empty.

Example: using default constructor in Java

Let’s say we have a class named `Employee` with this body:

public class Employee {
    public String name;
    public String lastName;
    public int id;

    }

If we add this class to a program and compile it, the compiler will refactor this class and will insert a default constructor, as the example below shows:

public class Employee {
    public String name;
    public String lastName;
    public int id;

    Employee (){}

}

As you can see, this is an empty constructor, which means there are no parameters and nobody.

Default Constructor vs No-args constructor

A default constructor that compiler adds to a class does have a body. It’s basically an empty body.

On the other hand, if we create a no-arg constructor, we can still define a body of that constructor and so that makes it different from the default constructor added by the compiler.

For this reason, we can’t say the default constructor and no-arg constructor are the same!

Example: using no-args constructor in Java

public class Employee {
    public String name;
    public String lastName;
    public int id;

    Employee (){
       this.name = "John";
       this.lastName = "Doe";
       this.id = 111111;
    }

}

As you can see, this constructor does not have a parameter, but it has a body and that makes it different from the default constructor.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies