Search code examples
javainheritancemultiple-choice

Multiple Choice Involving Inheritance in Java?


Consider the following declarations:

public class Dog0
{ public void doNothing(Dog1 a, Dog2 b) {} }

public class Dog1 extends Dog0 {}
public class Dog2 extends Dog1 {}

The following initializations appear in a different class:

Dog0 d0 = new Dog0 ();
Dog1 d1 = new Dog1 ();
Dog1 d2 = new Dog2 ();

Which of the following is a correct call to doNothing?

a) d0.doNothing(d0, d0);
b) d1.doNothing(d1, d1);
c) d1.doNothing(d2, d1);
d) d2.doNothing(d0, d0);
e) d2.doNothing(d2, d2); 

I think the answer is e) but I'm not sure. Could someone explain this to me? Thanks.


Solution

  • Correction

    None is the answer because for E to be the answer, Dog1 d2 = new Dog2(); should be turned into Dog2 d2 = new Dog2();

    But if it was, E would be the correct answer.

    doNothing accepts a Dog1, Dog2 as its arguments. A Dog2 is a Dog1, therefore, you can have a Dog2 in place of a Dog1.