Why do we still need to implement 'noArgsConstructor' if Java gives a non-parameterized constructor by default?

90 Views Asked by At

In Spring boot if we are creating a POJO class and we end up creating only a parameterized constructor and not any default constructor then Java will throw errors, why does this happen if Java provides a non-parameterized constructor by default why do I still have to implement it manually?

I tried not creating a non-parameterized constructor for a POJO and it threw an error when I created an object of the POJO class in another class.

3

There are 3 best solutions below

0
On BEST ANSWER

In Java, if you don't provide any constructor explicitly in your class, Java provides a default constructor. However, there's an exception to this rule. If you define any constructor explicitly in your class, Java won't provide a default constructor for you.

public class Employee{
    // No constructor defined explicitly

    // Other class members and methods
}

In this case, since no constructor is explicitly defined, Java will provide a default constructor for the Employee class.

However, if you define any constructor in your class, then Java won't provide a default constructor. For example:

public class Employee{
    String name;
    public Employee(String name) {
        // Constructor with parameter
    }

    // Other class members and methods
}

In this case, since a constructor is explicitly defined (Employee(String x)), Java won't provide a default constructor for Employee. If you need a default constructor along with your parameterized constructor, you'll need to define it explicitly:

public class Employee{
    String x
    public Employee(String name) {
        // Constructor with parameter
    }

    public Employee() {
        // Default constructor
    }

    // Other class members and methods
}

Now, the Employee has both a parameterized constructor and a default constructor.

2
On

Because it literally works this way.

Excerpt from Java specification:

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

For clarity

If a class contains any constructor declarations, then a default constructor is not declared.

0
On

In Java, when you create a class and don't explicitly define any constructors, Java provides a default no-argument constructor for you. This default constructor initializes member variables to their default values.

However, when you explicitly define a constructor in your class—whether it's a parameterized constructor or any other constructor—Java does not provide the default constructor anymore. If you want to use a no-argument constructor after defining any other constructors, you need to explicitly define it yourself. Java assumes that you are taking control over object initialization, and thus, it won't automatically generate a default constructor for you.