6

Does it make sense to write default constructor when it has no arguments, empty body and no other constructors exist?

The only benefit I can think of is reducing the risk of forgetting to add the default constructor when another one is created. But this error would show up anyway if the default constructor is actually being used (at least if the class is "internal" and not in a library), and if it isn't used it can be omitted (yagni).

What benefit can this have?

  • 6
    You need to declare it if you want to make it private or protected, but I imagine this is not want you had in mind. – Giorgio Jan 10 '14 at 12:17
  • @Giorgio. I came across this in someone else's code. And yes, there's nothing like keeping it private. – superM Jan 10 '14 at 12:22
7

There is no benefit unless you are interacting with a tool or framework that detects your class's declared methods and constructors via reflection and then silently does different things depending on whether it finds the default constructor or not. (I seem to remember that early versions of Spring or Hibernate did this.)

Otherwise, as you say, any inconsistency would be flagged by the compiler, so there is no point in declaring things that would be auto-generated anyway.

  • 10
    When I have to do this, I put a comment in the body on the constructor that says something like // No-args constructor required by *framework*. Helps cut down on confusion later. – Michael K Jan 10 '14 at 13:54
4

The only benefit I can foresee is that you can add specific documentation to this constructor, for instance to describe how to deal with the object after instantiation, etc...

In any other case, I do not think it is useful.

4

But this error would show up anyway if the default constructor is actually being used (at least in the class is "internal" and not in a library), and if it isn't used it can be omitted (yagni).

Xml deserialization. Yes the error would show up, but quite late - as an exception in runtime.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.