Java OCA OCP Practice Question 1925

Question

What would be the result of attempting to compile and run the following code?

class MyClass {/*from w  ww  .  j av  a 2 s.  c o  m*/
   int max(int x, int y) {
      if (x > y)
         return x;
      else
         return y;
   }
}

class MyClass2 extends MyClass {
   int max(int x, int y) {
      return 2 * super.max(x, y);
   }
}

class MyClass3 extends MyClass2 {
   int max(int x, int y) {
      return super.max(2 * x, 2 * y);
   }
}

// Filename: Main.java
public class Main {
   public static void main(String args[]) {
      MyClass2 c = new MyClass3();
      System.out.println(c.max(10, 20));
   }
}

Select 1 option

  • A. The code will fail to compile.
  • B. Runtime error.
  • C. The code will compile without errors and will print 80 when run.
  • D. The code will compile without errors and will print 40 when run.
  • E. The code will compile without errors and will print 20 when run.


Correct Option is  : C

Note

When the program is run, the main() method will call the max() method in MyClass3 with parameters 10 and 20 because the actual object referenced by 'c' is of class MyClass3.

This method will call the max () method in MyClass2 with the parameters 20 and 40.

The max() method in MyClass2 will in turn call the max() method in MyClass with the parameters 20 and 40.

The max() method in MyClass will return 40 to the max() method in MyClass2.

The max() method in MyClass2 will return 80 to the max() method in MyClass3.

And finally the max() of MyClass3 will return 80 in main() which will be printed out.




PreviousNext

Related