Wednesday, 27 June 2012

Java : Constructors must not invoke overridable methods

public class Override_Test {
   public static void main(String... args) {
      new Maruthi();
   }
}

class Car {
   String sName;

   Car() {
      sName = "Car Cycle";
      print();
   }

   public void print() {
      System.out.println("CAR : " + sName);
   }
}

class Maruthi extends Car {
   String sModel = "900";

   Maruthi() {
      sModel = "800";
   }

   @Override
   public void print() {
      System.out.println("MARUTHI : " + sModel);
   }
}


Let we guess the output of this implementation…

In Car constructor we are calling an overridden method print…

Moral : Constructors must not invoke overridable methods







Output :   MARUTHI : null