Java OCA OCP Practice Question 2839

Question

Given:

class MyClass {//  w w w.  ja v  a  2 s .com
   static String s = "";
   String name = "Tool ";

   MyClass(String arg) {
      this();
      s += name;
   }

   MyClass() {
      s += "gt ";
   }
}

public class Main extends MyClass {
   {
      name = "Main ";
   }

   Main(String arg) {
      s += name;
   }

   public static void main(String[] args) {
      new MyClass("hey ");
      new Main("hi ");
      System.out.println(s);
   }

   {
      name = "myMain ";
   }
}

What is the result?.

A.  Tool Main
B.  Tool myMain
C.  gt Tool Main
D.  gt Tool myMain
E.  gt Tool gt Main
F.  gt Tool gt myMain
G.  gt Tool gt Tool myMain
H.  Compilation fails.


F   is correct.

Note

The Main class has two instance initialization blocks, they run in the order they are encountered in the class, and they run when a new instance is created.

Now for the constructors; MyClass's 1-arg constructor calls it's no-arg constructor with the "this();" invocation.

Finally, when the Main is created, there is a call to MyClass's no-arg constructor because the compiler added a call to super().




PreviousNext

Related