1

Here's a code snippet from spring website.

I know that, If we write any parameterized constructor then the compiler won't add any default constructor. and there's never a need for explicitly adding a default constructor in our class.

But then why here they have written a default one.

@Entity
class Employee {

  private @Id @GeneratedValue Long id;
  private String name;
  private String role;

  Employee() {}

  Employee(String name, String role) {

    this.name = name;
    this.role = role;
  }
VivekKumar
  • 11
  • 3
  • 5
    You already said it. The compiler doesn't provide a default constructor. So if one is needed, then you have to declare it manually. – markspace Mar 01 '21 at 02:06
  • 3
    It's common for frameworks which create instances via reflection to first create an instance with empty fields, and then set the field values reflectively. This requires a default constructor. – tgdavies Mar 01 '21 at 02:09
  • 4
    If you want to know exactly why in this case: set a breakpoint if the default constructor and see when it's called. – tgdavies Mar 01 '21 at 02:09
  • 1
    Does this answer your question? [Why does Hibernate require no argument constructor?](https://stackoverflow.com/questions/2935826/why-does-hibernate-require-no-argument-constructor) – jms Mar 01 '21 at 03:43

0 Answers0