Constructors shouldn't call overridables

Constructors should not call an overridable method - that is, they should only call methods that are private, static, or final.

The reason why is best illustrated with a bit of code:


public final class ConstructorOverridable {

  public static void main(String... aArgs){
    log("BUILD AN ANIMAL :");
    Animal animal = new Animal();
    log(" ");
    log("BUILD A FISH :");
    Animal fish = new Fish();
  }
  
  // PRIVATE
  private static void log(Object aObject){
    System.out.println(String.valueOf(aObject));
  }
  
  private static class Animal{
    Animal(){
      log("Animal ctor");
      //call an overridable method from ctor - dangerous
      perform();
    }
    void perform(){
      log("Animal perform.");
    }
  }
  
  private static class Fish extends Animal {
    Fish(){
      //every constructor has an implicit call to super(); for first line 
      super();
      log("Fish ctor. This is the earliest Tail Shape can be initialized.");
    }
    void perform(){
      //in general, this method can depend on Fish data
      log("Fish perform. Can fail since Tail Shape is : " + fTailShape);
    }
    private String fTailShape;
  }
}
 

An example run of this class demonstrates the problem:
BUILD AN ANIMAL :
Animal ctor
Animal perform.
 
BUILD A FISH :
Animal ctor
Fish perform. Can fail since Tail Shape is : null
Fish ctor. This is the earliest Tail Shape can be initialized.

See Also :
Constructors in general
Designing for subclassing
Overridable methods need special care
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -