Java OCA OCP Practice Question 385

Question

Consider the following program:

class MyClass  { 
  public void play () throws Exception    { 
    System.out.println ("Playing..."); 
   } /*w  w  w  .j  a  v  a 2 s .  c  o  m*/
} 

class MySubClass extends MyClass  { 
   public void play (String ball)     { 
      System.out.println ("Playing MySubClass with "+ball);       
    } 
} 

public class Main  { 
   public static void main (String [] args) throws Exception   { 
       MyClass g = new MySubClass (); 
       // 1 
       MySubClass s =  (MySubClass) g; 
       // 2 
    } 
} 

Which of the given options can be inserted at // 1 and //2?

Select 2 options

  • A. It will not compile as it is.
  • B. It will throw an Exception at runtime if it is run as it is.
  • C. g.play (); at // 1 and s.play ("ball"); at //2
  • D. g.play (); at // 1 and s.play (); at //2
  • E. g.play ("ball"); at // 1 and s.play ("ball"); at //2


Correct Options are  : C D

Note

A. is wrong. There is no problem with the existing code.

B. is wrong. MySubClass s = (MySubClass) g; is a valid because g does refer to an object of class MySubClass at run time.

So there will be no exception at run time.

C. is correct.

This is valid because g is of type MyClass, which has the no-args play method and s is of type MySubClass, which has defined play (String ) method.

D. is correct.

This is valid because g is of type MyClass, which has the no-args play method and s is of type MySubClass, which inherits that method.

E. is wrong.

g.play ("ball") is not valid because even though the object referred to by g is of class MySubClass, the reference type of g is MyClass, which does not have play (String ) method.




PreviousNext

Related