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
publi…


This content originally appeared on DEV Community and was authored by gaurbprajapati

🧩 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;
    }
}

Constructors are called when you create an object:

Person person = new Person("Gaurav");

🧱 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;
}

The Java compiler automatically adds:

public Employee() {
    super(); // calls Object class constructor
}

So you can still do:

Employee e = new Employee(); // ✅ Works fine

❌ 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;
    }
}

Now:

Employee e = new Employee(); // ❌ Compilation error

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();
   }
  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!");
    }
}

✅ 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;
    }
}

If missing:

org.hibernate.InstantiationException: No default constructor for entity class

🟨 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
}

If you omit it:

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

💬 7. Examples

✅ Case 1 – No constructor defined

public class Car {
    private String brand;
}
// Compiler adds default constructor
Car c = new Car(); // ✅ Works

❌ 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

✅ 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

🧩 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

🧾 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;
    }
}

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.


This content originally appeared on DEV Community and was authored by gaurbprajapati


Print Share Comment Cite Upload Translate Updates
APA

gaurbprajapati | Sciencx (2025-10-22T20:01:49+00:00) Default Constructor in Java – Complete Explanation. Retrieved from https://www.scien.cx/2025/10/22/default-constructor-in-java-complete-explanation/

MLA
" » Default Constructor in Java – Complete Explanation." gaurbprajapati | Sciencx - Wednesday October 22, 2025, https://www.scien.cx/2025/10/22/default-constructor-in-java-complete-explanation/
HARVARD
gaurbprajapati | Sciencx Wednesday October 22, 2025 » Default Constructor in Java – Complete Explanation., viewed ,<https://www.scien.cx/2025/10/22/default-constructor-in-java-complete-explanation/>
VANCOUVER
gaurbprajapati | Sciencx - » Default Constructor in Java – Complete Explanation. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/10/22/default-constructor-in-java-complete-explanation/
CHICAGO
" » Default Constructor in Java – Complete Explanation." gaurbprajapati | Sciencx - Accessed . https://www.scien.cx/2025/10/22/default-constructor-in-java-complete-explanation/
IEEE
" » Default Constructor in Java – Complete Explanation." gaurbprajapati | Sciencx [Online]. Available: https://www.scien.cx/2025/10/22/default-constructor-in-java-complete-explanation/. [Accessed: ]
rf:citation
» Default Constructor in Java – Complete Explanation | gaurbprajapati | Sciencx | https://www.scien.cx/2025/10/22/default-constructor-in-java-complete-explanation/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.