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() { super(); } }
—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:
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.
Comments
There is 1 comment on this post. Comments are closed.
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!!