John Topley’s Weblog

Java Default Constructors

There seems to be a lot of confusion amongst Java programmers as to what consitutes a default constructor, a no-argument constructor and what the difference is between them. For example, I keep coming across Java code similar to this:

public class OmniCognateNeutronWrangler
   * Default constructor.
  public OmniCognateNeutronWrangler()

—The Javadoc for this class is incorrect. The source code for the class contains a no-argument constructor, not a default constructor. The default constructor is the constructor that is generated automatically for you behind the scenes by the Java compiler if you create a class that has no constructors. It's possible to see this in action.

Write a class that has no constructors and compile it:

 * Empty class.
public class NoConstructor

Next, use the javap command-line tool that comes with the JDK to decompile the compiled .class file using the -c switch, as shown below:

Note the invokespecial #1 line that calls Object's constructor.
The results of decompiling a class without constructors

I've used the type command to show the contents of the source file to prove that there's no trickery going on. If you think I've doctored the screen shot then do try this at home kids.

The decompiler lists the Java source code for the class and notice that the compiler has silently inserted a default constructor. The -c switch makes the decompiler list the corresponding JVM bytecodes. The line we're interested in is the invokespecial #1 call to the constructor in java.lang.Object: in other words, a default constructor has been generated for us and all it does is invoke the superclass constructor.


There is 1 comment on this post. Comments are closed.

  • avatar Hibernate Master
    27 June 2005 at 17:12

    Thanks for the insightful comments.... However, I tried your "handy" trick at home and I'm positive you DOCTORED the screen shot. Nice try, better luck next time!!

If you think I've doctored the screen shot then do try this at home kids.


  • Jan
  • Feb
  • Mar
  • Apr
  • May
  • Jun
  • Jul
  • Aug
  • Sep
  • Oct
  • Nov
  • Dec
  • 2019
  • 2018
  • 2017
  • 2016
  • 2015
  • 2014

More Archives

Sign In