This post originated from an RSS feed registered with Java Buzz
by John Topley.
Original Post: Java Default Constructors
Feed Title: John Topley's Weblog
Feed URL: http://johntopley.com/posts.atom
Feed Description: John Topley's Weblog - some articles on Ruby on Rails development.
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:
Note the invokespecial #1 line that calls Object's constructor.
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.