Saturday, August 28, 2010

Polymorphic calls and co-variant returns can work together

Courtesy of Sun Web Learning Center


Given:

1. class Animal { Animal getOne() { return new Animal(); } }
2. class Dog extends Animal {
3.   // insert code here
4. }
5.
6. class AnimalTest {
7.   public static void main(String [] args) {
8.     Animal [] animal = { new Animal(), new Dog() } ;
9.     for( Animal a : animal) {
10.       Animal x = a.getOne();
11.     }
12.   }
13. }

And the code:

3a.  Dog getOne() { return new Dog(); }
3b.  Animal getOne() { return new Dog(); }

Which, inserted at line 3, will compile and run with no exceptions?


A Only line 3a
B Only line 3b
C Either line 3a or 3b
D Both line 3a and 3b added together.

C is correct. Polymorphic calls and co-variant returns can work together.

No comments:

Post a Comment