0

Learned List<Dog> is not a sub-class of List<Animal> for a number of reasons (Is List<Dog> a subclass of List<Animal>? Why aren't Java's generics implicitly polymorphic? and create a list of list of Strings in Java)

But I tested it seems array works -- an instance of Dogs[] could be assigned to an instance of Animal[]. But doesn't array has the same issue of put an instance of Cat into Dog array?

See my below code for TestArray which works for array, but TestList does not work for List<T>.

Any thoughts?

Source code in Java,

import java.util.*;
public class TestInheritance {

    void TestArray() {
        Dog[] dogs = new Dog[3];
        Animal[] ans = dogs;
        Cat c = new Cat();
        ans[2] = c;
    }

    void TestList() {
        List<Dog> dogs = new ArrayList<Dog>();
        /*
         * compile error in below statement, Type mismatch: cannot convert from List<TestInheritance.Dog>
         * to List<TestInheritance.Animal>
         */
        List<Animal> ans = dogs;
    }

    class Animal {
        Animal() {

        }

        void WhoAmI() {
            System.out.println("I am Animal!");
        }
    }

    class Dog extends Animal {
        Dog() {

        }

        void Dog() {
            System.out.println("I am Dog!");
        }
    }

    class Cat extends Animal {
        Cat() {

        }

        void Cat() {
            System.out.println("I am Cat!");
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}
Community
  • 1
  • 1
Lin Ma
  • 9,739
  • 32
  • 105
  • 175

0 Answers0