What will the following program print when compiled and run?
class MyClass{ //from ww w. ja v a2s.c om public void play () throws Exception{ System.out.println ("Playing..."); } } public class MySubClass extends MyClass{ public void play (){ System.out.println ("Playing MySubClass..."); } public static void main (String [] args){ MyClass g = new MySubClass (); g.play (); } }
Select 1 option
Correct Option is : A
Observe that play()
in MyClass declares Exception in its throws clause.
class MySubClass overrides the play()
method without any throws clause.
This is valid because a list of no exception is a valid subset of a list of exceptions thrown by the superclass method.
Now, even though the actual object referred to by 'g' is of class MySubClass, the class of the variable g is of class MyClass.
At compile time, compiler assumes that g.play()
might throw an exception, because MyClass's play method declares it, and thus expects this call to be either wrapped in a try-catch or the main method to have a throws clause for the main()
method.