Java OCA OCP Practice Question 850

Question

What can be inserted at // 1 and //2 in the code below so that it can compile without errors:

class Pet{ /*from   w w  w . j  a v  a  2 s. c  om*/
    String name; 
    Pet (String nm){ 
        this.name = nm; 
     } 
} 

class Fish extends Pet{ 
    Fish (){ 
        //1  
     } 
    Fish (String nm){ 
        //2 
     } 
} 
public class Main  { 
       public static void main (String [] args)  { 
          Fish b = new Fish ("mydoll"); 
       } 
} 

Select 2 options

  • A. this ("unknown"); at 1 and super (nm); at 2
  • B. super ("unknown"); at 1 and super (nm); at 2
  • C. super (); at 1 and super (nm); at 2
  • D. super (); at 1 and Pet (nm); at 2
  • E. super ("unknown"); at 1 and this (nm); at 2
  • F. Pet (); at 1 and Pet (nm); at 2


Correct Options are  : A B

Note

Since the super class Pet explicitly defines a constructor, compiler will not provide the default no-args constructor.

Each of Fish's constructor must directly or indirectly call Pet's string argument constructor, otherwise it will not compile.

Although not relevant for this question, it is interesting to know that super (name); at // 1 or //2, would not be valid because name is defined in the superclass and so it cannot be used by a subclass until super class's constructor has executed.

For the same reason, this (name); cannot be used either.




PreviousNext

Related