Monday 12 December 2011

Implicit Default Constructor - good or bad?

Everyone who knows Java, knows that if you do not define a constructor in a class, the default constructor is implicitly created by the compiler.[1]

Is this a good thing or a bad thing?

Good thing:

  • we need a constructor to instantiate an object, and if we forget to make one we can simply use the default constructor.

Bad thing:
  • creating a new constructor with arguments, automatically will make the compiler NOT create the implicit default constructor, perhaps causing breakage in your program/application.

So, should we do the following?

package mrbear;

public class Main
{

    /**
     * Explicit Default Constructor. Required.
     * Defined here to prevent problems when
     * new constructor(s) with different arguments is/are added.
     */

    public Main()
    {
    }

}

I know for a fact, for example, that Hibernate requires entities to have some sort of default constructor, so Hibernate can create objects using reflection. [2]

You'd see something in the log like:

10:54:15,575 INFO [PojoInstantiator] no default (no-argument) constructor for class: mrbear.Main (class must be instantiated by Interceptor)

References

[1] Providing Constructors for Your Classes
http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
[2] Hibernate : Chapter 4. Persistent Classes
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/persistent-classes.html

No comments:

Post a Comment