DEV Community

gaurbprajapati
gaurbprajapati

Posted on

Default Constructor in Java – Complete Explanation

🧩 1. What is a Constructor?

A constructor in Java is a special method used to initialize objects.
It has the same name as the class and no return type.

Example:

public class Person {
    private String name;

    // Constructor
    public Person(String name) {
        this.name = name;
    }
}
Enter fullscreen mode Exit fullscreen mode

Constructors are called when you create an object:

Person person = new Person("Gaurav");
Enter fullscreen mode Exit fullscreen mode

🧱 2. What is a Default Constructor?

A default constructor is a no-argument constructor that Java automatically adds if you do not define any constructor in your class.

Example:

public class Employee {
    private int id;
    private String name;
}
Enter fullscreen mode Exit fullscreen mode

The Java compiler automatically adds:

public Employee() {
    super(); // calls Object class constructor
}
Enter fullscreen mode Exit fullscreen mode

So you can still do:

Employee e = new Employee(); // βœ… Works fine
Enter fullscreen mode Exit fullscreen mode

❌ 3. When Default Constructor is NOT Added Automatically

If you explicitly define any constructor (parameterized or not),
the compiler does not add the default (no-arg) constructor.

Example:

public class Employee {
    private String name;

    public Employee(String name) {
        this.name = name;
    }
}
Enter fullscreen mode Exit fullscreen mode

Now:

Employee e = new Employee(); // ❌ Compilation error
Enter fullscreen mode Exit fullscreen mode

Reason:
Because you defined your own constructor, Java assumes you’re handling all initialization logic manually.


βš™οΈ 4. How It Works (Behind the Scenes)

When you compile a Java class:

  1. The Java compiler checks whether you defined any constructor.
  2. If no constructor exists, it automatically injects:
   public ClassName() {
       super();
   }
Enter fullscreen mode Exit fullscreen mode
  1. During runtime, when new keyword is used, this constructor initializes the object.

🧠 5. Why Default Constructor is Important

Many frameworks (like Spring Boot, Hibernate, Jackson) use reflection to create objects.
Reflection means they create objects without calling new directly, but by inspecting class metadata at runtime.

These frameworks depend on a no-argument constructor because:

  • They create the object first.
  • Then, set the fields (via setters or field access).

Without a default constructor, frameworks cannot instantiate your class dynamically.


πŸš€ 6. Use Cases in Popular Frameworks

🟩 a. Spring Boot

Spring creates beans using reflection.
If your bean has only a parameterized constructor, you must provide parameters via @Autowired or @Value.
If not, Spring fails to instantiate the bean.

Example:

@Component
public class MyService {
    public MyService() {
        System.out.println("Bean created by Spring!");
    }
}
Enter fullscreen mode Exit fullscreen mode

βœ… Works fine β€” Spring uses default constructor.


🟧 b. Hibernate / JPA

JPA entities must have a public or protected no-arg constructor.

@Entity
public class User {
    @Id
    private Long id;
    private String name;

    public User() {}  // Required by JPA

    public User(String name) {
        this.name = name;
    }
}
Enter fullscreen mode Exit fullscreen mode

If missing:

org.hibernate.InstantiationException: No default constructor for entity class
Enter fullscreen mode Exit fullscreen mode

🟨 c. Jackson (JSON Serialization/Deserialization)

When converting JSON to a Java object (@RequestBody, ObjectMapper.readValue()),
Jackson first calls the no-arg constructor, then populates fields.

public class Product {
    private String name;
    private double price;

    public Product() {}  // Required by Jackson
}
Enter fullscreen mode Exit fullscreen mode

If you omit it:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
Cannot construct instance of Product (no Creators, like default constructor, exist)
Enter fullscreen mode Exit fullscreen mode

πŸ’¬ 7. Examples

βœ… Case 1 – No constructor defined

public class Car {
    private String brand;
}
// Compiler adds default constructor
Car c = new Car(); // βœ… Works
Enter fullscreen mode Exit fullscreen mode

❌ Case 2 – Parameterized constructor only

public class Car {
    private String brand;
    public Car(String brand) {
        this.brand = brand;
    }
}
// No default constructor
Car c = new Car(); // ❌ Error
Enter fullscreen mode Exit fullscreen mode

βœ… Case 3 – Explicitly adding both

public class Car {
    private String brand;
    public Car() {} // default
    public Car(String brand) {
        this.brand = brand;
    }
}
Car c1 = new Car(); // βœ… Works
Car c2 = new Car("BMW"); // βœ… Works
Enter fullscreen mode Exit fullscreen mode

🧩 8. Summary Table

Scenario Default Constructor Added by Compiler Can Create Object Using new Class() Framework Compatibility
No constructor defined βœ… Yes βœ… Yes βœ… Works fine
Parameterized constructor defined ❌ No ❌ Compilation error ❌ Frameworks fail to instantiate
Explicit no-arg constructor defined βœ… Already present βœ… Yes βœ… Best practice

πŸ’‘ 9. Best Practices

  1. βœ… Always include a no-argument constructor in POJOs, DTOs, Entities.
  2. βš™οΈ If you define any parameterized constructor, manually add a default one too.
  3. 🧱 For immutable classes, use a builder pattern instead of default constructor.
  4. 🧩 In frameworks like Spring Boot or Hibernate β€” always ensure reflection can instantiate your classes.

πŸ” 10. Quick Visual Reference

          +-----------------------------+
          |   Java Compiler Behavior    |
          +-----------------------------+
                |
                v
      [No constructor defined]
                |
                v
       Adds public ClassName() {}
                |
                v
     Object creation works normally

      [Parameterized constructor defined]
                |
                v
     Compiler does NOT add default one
                |
                v
     Must manually create no-arg constructor
Enter fullscreen mode Exit fullscreen mode

🧾 Example in Spring Boot Context

@Component
public class ConfigTestClass {

    private final String name;

    // Inject value from application.properties
    public ConfigTestClass(@Value("${app.name}") String name) {
        this.name = name;
    }
}
Enter fullscreen mode Exit fullscreen mode

If you add no other constructor β€” fine.
But if another framework (e.g., Jackson) tries to instantiate this class for deserialization β€”
you’ll need a no-arg constructor.


🧠 Key Takeaways

  • Java automatically adds a default no-arg constructor only if no other constructors are defined.
  • Frameworks like Spring, Hibernate, Jackson rely on this for reflection-based instantiation.
  • Always add an explicit no-arg constructor in entities and POJOs when using frameworks.

Top comments (0)