Widget.java - Default Constructor Demo

When you create a class and don't define any constructors, Java adds a default, no-arg (parameterless) constructor.  But if you later add any constructors to your class, this default constuctor is no longer added automatically.

Download the two .java files below and compile them both.  There should be no error when compiling or running.  Next remove the outer comments in Widget.java and recompile.  This should work but generate a run-time exception!  If you try to recompile WidgetTest.java, that will not work.

Once you define any constructors yourself you need to add back the no-arg constructor if you want it.  Un-comment out that constructor in Widget.java and everything should work again.


Download Widget.java

class Widget
{
   String name;

   /*
   public Widget ( String name )  { this.name = name; }

   // public Widget () {}
   */
}

 


WidgetTest.java

Download WidgetTest.java

class WidgetTest
{
   public static void main ( String [] args )
   {
      Widget w = new Widget();  // invokes no-arg constructor
      System.out.println( "Done constructing a widget!" );
   }

}