Monday, February 06, 2006

Sequence of constructor invocation in Java

Consider the following scenario:

    
Class Foo {
String name;
}

Class FooBar extends Foo {
String address;

FooBar() {
// constructor that takes no arguments
}

// constructor that takes arguments
FooBar(String address) {
this.address = address;
}
}


One can make several observations here:

  1. If the base class does not explicitly define any constructors, then the subclass constructors implicitly call the default base class constructor (supplied by the compiler) that takes no arguments.
  2. If the base class were to only define a constructor that takes argument(s), then the subclass constructors should explicitly call that constructor. Otherwise it will result in a compile time error.
  3. If the base class defines both a constructor that takes no arguments and a constructor that takes argument(s), the subclass constructors will implicitly invoke the constructor that takes no arguments unless it is explicitly coded to call the constructor that takes arguments.

0 Comments:

Post a Comment

<< Home