question 11

Posted Thursday, September 03, 2009 by SacrosanctBlood in

I want

1.    The output of the below program. I know you can execute it and
see, but keep it as last option. Try to analyze the problem and
determine the output.
2.    Why is the resultant output that way and what is the moral of
the story?

//Parent.java

import java.util.Date;

public class Parent {

      public Parent(){

            printTodaysDate();

      }

      public void printTodaysDate(){

            System.out.println(new Date());

      }

}

//Child.java

import java.util.Date;

public class Child extends Parent{

      private Date date;     

      public Child(){

            date = new Date(2000,12,31);

      }

      public void printTodaysDate() {

            yadiYadiDaPrintSomeDate();

      }

      public void yadiYadiDaPrintSomeDate(){

            System.out.println(date);

      }

      /**

       * @param args

       */

      public static void main(String[] args) {

            Child d = new Child();

            d.printTodaysDate();// What does this print

      }

}



1 comment(s) to... “question 11”

1 comments:

SacrosanctBlood said...

1.

Output:

null

Thu Jan 31 00:00:00 IST 3901



2.

Sequence of execution:

Super class Parent constructor called

Constructor calls overridden printTodaysDate

Prints null, as date not init in child, as still flow of execution in
parent constructor

Child constructor is called

Date is initialized

d.printTodaysDate(); prints the date



Moral: Do not call any overridable methods from constructor, that may
lead to undesired behaviour



Post a Comment