Java OCA OCP Practice Question 1405

Question

Consider the following code:

class MyClass { //from w  w  w . java 2  s  . c om
   MyClass ()  {  print ();    } 
   void print ()  { System.out.println ("MyClass");  } 
} 
class Main extends MyClass { 
   int i =   Math .round (3.5f); 
   public static void main (String [] args){ 
      MyClass a = new Main (); 
      a.print (); 
    } 
   void print ()  { System.out.println (i);  } 
} 

What will be the output when class Main is run ?

Select 1 option

  • A. It will print MyClass, 4.
  • B. It will print MyClass, MyClass
  • C. It will print 0, 4
  • D. It will print 4, 4
  • E. None of the above.


Correct Option is  : C

Note

Note that method print () is overridden in class Main.

Due to polymorphism, the method to be executed is selected depending on the class of the actual object.

Here, when an object of class Main is created, first MyClass's constructor is called, which in turn calls print ().

Now, since the class of actual object is Main, Main's print () is selected.

At this point of time, variable i has not been initialized (because we are still initializing MyClass at this point), so its default value i.e. 0 is printed.

This happens because the method print () is non-private, hence polymorphic.

Finally, 4 is printed.




PreviousNext

Related