Search code examples
javadefault-constructor

Is there a reason to explicitly code a default constructor when there are no other constructors?


I recently saw this constructor in a class:

public MyClass(){ }

There were no other constructors.

Is there a reason for this? Java automatically creates a default constructor, so why would you declare one explicitly? Or is this considered good practice in the same way as using braces for single-statement if statements - in case other constructors are added later and you forget that you don't have a default...?


Solution

  • A couple minor points that aren't likely to be why you saw it in this case.

    • It gives you something to set a breakpoint on.
    • You could make it non-public

    As far as "in case other constructors are added later and you forget that you don't have a default" - that might be a reason, I suppose. But if a non-default constructor were added, any code that used the default constructor would fail to compile, so the guy adding the new constrcutor would generally need to also add a defintion for the default ctor as well.

    Then again, I can't think of any particular harm in having the empty ctor defined (though now that I've typed that, I get a feeling that someone might point out some corner of C++ where it could bite you).