Java OCA OCP Practice Question 1570

Question

What should be placed in the two blanks so that the following code will compile without errors:

class MyBaseClass{
    public void m () throws Exception{
        throw new Exception ();
     }/*ww  w.  j  ava 2  s.co m*/
}
class MyClass extends MyBaseClass{
    public void m ()  {
     }
}
public class Main  {
    public static void main (String [] args)  {
        ______ obj = new ______ ();
        obj.m ();
     }
}

Select 1 option

  • A. MyBaseClass and MyClass
  • B. MyBaseClass and MyBaseClass
  • C. MyClass and MyClass
  • D. MyClass and MyBaseClass
  • E. Nothing will make the code compile.


Correct Option is  : C

Note

The overriding method may choose to have no throws clause even if the overridden method has a throws clause.

if you define s of type MyBaseClass, the call s.m () will have to be wrapped into a try/catch because main () doesn't have a throws clause.

But if you define s of class MyClass, there is no need of try catch because MyClass's m () does not throw an exception.

If the class of s is MyClass, you cannot assign it an object of class MyBaseClass because MyBaseClass is a superclass of MyClass.

So the only option is to do:

MyClass s = new MyClass ();



PreviousNext

Related