Java OCA OCP Practice Question 3054

Question

Given:

class Shape {
   protected Shape() {
      System.out.print("ms ");
   }/*  ww  w  . ja  va 2  s .c om*/
}

public class Main extends Shape {
   private Main() {
      System.out.print("mt ");
   }

   public static void main(String[] args) {
      new Shape();
      class MyInner {
         private MyInner() {
            System.out.print("mi ");
         }

         {
            new Main();
         }
         {
            new Shape();
         }
      }
      new MyInner();
   }
}

What is the result?

  • A. ms mi mt ms
  • B. ms mt ms mi
  • C. ms mi ms mt ms
  • D. ms ms mt ms mi
  • E. Compilation fails.
  • F. An exception is thrown at runtime.


D is correct.

Note

Main can access Shape's protected constructor, and MyInner can access Main's private constructor.

As far as the order goes, the MyInner code is invoked after it's declared.

When the MyInner code does run, the instance init blocks run after MyInner's constructor's call to super(), and before the rest of the constructor runs.

Remember that a new instance of Main calls Shape's constructor.




PreviousNext

Related