Java OCA OCP Practice Question 1033

Question

What is the output of the following code?

1: public abstract class MyClass { 
2:   public abstract void dive() {}; 
3:   public static void main(String[] args) { 
4:     MyClass m = new MySubClass(); 
5:     m.dive(); //w  w w .j  a v a2 s .  c o m
6:   } 
7: } 
8: class MySubClass extends MyClass { 
9:   public void dive(int depth) { System.out.println("MySubClass diving"); } 
10: } 
  • A. MySubClass diving
  • B. The code will not compile because of line 2.
  • C. The code will not compile because of line 8.
  • D. The code will not compile because of line 9.
  • E. The output cannot be determined from the code provided.


B.

Note

This may look like a complex question, but it is actually quite easy.

Line 2 contains an invalid definition of an abstract method.

Abstract methods cannot contain a body, so the code will not compile and option B is the correct answer.

If the body {} was removed from line 2, the code would still not compile, although it would be line 8 that would throw the compilation error.

Since dive() in MyClass is abstract and MySubClass extends MyClass, then it must implement an overridden version of dive().

The method on line 9 is an overloaded version of dive(), not an overridden version, so MySubClass is an invalid subclass and will not compile.




PreviousNext

Related