Always write a no-arg constructor in a java class

When a java class contains no constructor, the compiler will generate a default no-arg constructor. But it's always a good idea to explicitly write this no-arg constructor. Some good reasons:

1. To future-proof this class and all its subclasses.

Constructors in all subclasses always calls the superclass' constructor at the first line, explicitly or implicitly. If the superclass does not define any explicit constructor, a default no-arg constructor is called. Therefore, subclasses rely on the fact that a no-arg constructor exists in the superclass. Otherwise, they will fail to compile.

However, the default no-arg constructor will not be generated by javac when the class defines any constructor. So it's likely that when a parametered constructor is added to superclass in the future, the no-arg constructor cease to exist, which will cause subclasses to fail to compile.

2. To future-proof conformance to certain Java standards.

In many Java standards or specifications, components are required to have a no-arg constructor. For example, JavaBeans, EJB, Servlet, JPA, etc, because these component classes are instantiated and managed by their respective containers. For the same reason as above, a default no-arg constructor may exist now by disappear in the future. By defining a no-arg constructor, your code is more maintainable and robust.

3. It's easy. Most IDEs like Eclipse or NetBeans can generate it for you.

4. Control its access modifier, making it private or protected, rather than public.

The generated no-arg constructor is always public, which may not be the best. For example, for utility classes that only contains static methods, clients never need to instantiate instances. Or for singleton, you also want to prevent external instantiation. Therefore, a private (in some rare cases, protected) no-arg constructor is more appropriate.

Followers

Pageviews Last 7 Days