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: }
B.
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.