Java OCA OCP Practice Question 1823

Question

What will the following program print when run?.



class MyClass {//from www .jav a2s.c om
  MyClass() { this("1", "2"); }

  MyClass(String s, String t) { this(s + t); }

  MyClass(String s) { System.out.println(s); }
 }

class MyClass2 extends MyClass {
  MyClass2(String s) { System.out.println(s); }

  MyClass2(String s, String t) { this(t + s + "3"); }

  MyClass2() { super("4"); };
 }

// Filename: Main.java
public class Main {
  public static void main(String[] args) {
    MyClass2 b = new MyClass2("Test");
  }
 }

Select the one correct answer.

  • (a) It will just print Test.
  • (b) It will print Test followed by Test.
  • (c) It will print 123 followed by Test.
  • (d) It will print 12 followed by Test.
  • (e) It will print 4 followed by Test.


(d)

Note

The program will print 12 followed by Test.

When the main() method is executed, it will create a new instance of MyClass2 by passing "Test" as argument.

This results in a call to the constructor of MyClass2 that has one String parameter.

The constructor does not explicitly call any superclass constructor but, instead, the default constructor of the superclass MyClass is called implicitly.

The default constructor of MyClass calls the constructor in MyClass that has two String parameters, passing it the argument list ("1", "2").

This constructor calls the constructor with one String parameter, passing the argument "12".

This constructor prints the argument.

Now the execution of all the constructors in MyClass is completed, and execution continues in the constructor of MyClass2.

This constructor now prints the original argument "Test" and returns to the main() method.




PreviousNext

Related