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
Correct Option is : C
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.