Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

java - 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...?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...