Friday 19 July 2013

OCJP Model Question and Answer - Inheritence ,Constructor

Question:

 class Atom {
 Atom() { System.out.print("atom "); }
 }
 class Rock extends Atom {
 Rock(String type) { System.out.print(type); }
 }
 public class Mountain extends Rock {
 Mountain() {
 super("granite ");
 new Rock("granite ");
 }
 public static void main(String[] a) { new Mountain(); }
 }

What is the result?

A. Compilation fails.
B. atom granite
C. granite granite
D. atom granite granite
E. An exception is thrown at runtime.
F. atom granite atom granite


Concepts to know:

Whenever an object is created for a child class , its constructor should be executed.But the order of
execution of constructors in case of inheritance will be ,

Default Constructor of parent is executed first and then default constructor of the child in the hierarchy tree.


Hence here ,

Hierarchy--   Atom


                     Rock


                    Mountain

Hence when object for Mountain is created  , order of execution of methods are as follows,

Atom() { System.out.print("atom "); }                                                                                                                        --   o/p      atom

Rock()

Mountain()
{
  super("granite");       // will call Rock(String type) hence yields  
                                                                   -- o/p       granite

  new Rock("granite ");  // will call  Atom() { System.out.print("atom "); }
                                                                   --   o/p        atom     ,then calls
            // Rock(String type)                        --  o/p granite

                         
 }


Ans : (F)  atom granite atom granite

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...