Java OCA OCP Practice Question 1937

Question

What will be the result of compiling and running the following program?.

public class Main {
 public static void main(String[] args) {
   MyClass ref1 = new MyClass3();
   MyClass2 ref2 = (MyClass2) ref1;//from   w  w w.  j  a  v  a2  s. co m
   System.out.println(ref2.g());
 }
}

class MyClass {
 private int f() { return 0; }
 public int g() { return 3; }
}
class MyClass2 extends MyClass {
 private int f() { return 1; }
 public int g() { return f(); }
}
class MyClass3 extends MyClass2 {
 public int f() { return 2; }
}

Select the one correct answer.

  • (a) The program will fail to compile.
  • (b) The program will compile and print 0, when run.
  • (c) The program will compile and print 1, when run.
  • (d) The program will compile and print 2, when run.
  • (e) The program will compile and print 3, when run.


(c)

Note

The program will print 1 when run.

The f() methods in MyClass and MyClass2 are private and are not accessible by the subclasses.

Because of this, the subclasses cannot overload or override these methods, but simply define new methods with the same signature.

The object being called is of the class MyClass3.

The reference used to access the object is of the type MyClass2.

Since MyClass2 contains a method g(), the method call will be allowed at compile time.

During execution it is determined that the object is of the class MyClass3, and dynamic method lookup will cause the overridden method g() in MyClass2 to be executed.

This method calls a method named f.

It can be determined during compilation that this can only refer to the f() method in MyClass2, since the method is private and cannot be overridden.

This method returns the value 1, which is printed.




PreviousNext

Related