It won't work because the type of the array is Animal, which means the objects in the array are of type Animal. You're assigning an individual element which is either a Dog or Cat to a reference of that particular animal, but the object is of type Animal, even though the actual element is a Dog or a Cat. The compiler doesn't know what kind of Animal it is, without a cast.
For that statement to work, you need a cast to the appropriate type.
Dog lassie = (Dog) animals[0];
Cat fluffy = (Cat) animals[1];
Polymorphism though, isn't really used in this manner, since the idea is that you as the user, don't need to know the specific type of Animal, just that it's an Animal.
Suppose your Animal class defined an abstract method called speak() and your subclasses both implemented it, System.out.println("Woof") for a Dog and System.out.println("Meow") for a Cat, to keep it simple.
Example:
public abstract class Animal {
public abstract void speak();
}
public class Dog extends Animal {
@Override
public void speak() {
System.out.println("Woof!");
}
}
public class Cat extends Animal {
@Override
public void speak() {
System.out.println("Meow!");
}
}
If you then had your array as such:
Animal[] animals = new Animal[20];
animals[0] = new Dog();
animals[1] = new Cat();
for (Animal a : animals) {
a.speak(); // you don't know what Animal it is, but the proper speak method will be called.
}
animals[0]always holds a Dog.if(Math.random() < 0.5) animals[0] = new Dog(); else animals[0] = new Cat(); Dog d = animals[0];