What is Java empty constructor?

522    Asked by JuliaGraham in Java , Asked on Oct 12, 2022

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?


Answered by debbie Jha

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 Java empty 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.



Your Answer

Interviews

Parent Categories