KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
Who could me explain this? I have these couple of classes: abstract class Animal { public void eat() { System.out.println("Animal is eating"); } } class Dog extends Animal { public void woof() { System.out.println("woof"); } } class Cat extends Animal { public void meow() { System.out.println("meow"); } } And this is the action: import java.util.ArrayList; import java.util.List; public class TestClass { public static void main(String[] args) { new TestClass().go(); } public void go() { List<Dog> animals = new ArrayList<Dog>(); animals.add(new Dog()); animals.add(new Dog()); doAction(animals); } public <T extends Animal> void doAction(List<T> animals) { animals.add((T) new Cat()); // why is it possible? // Variable **animals** is List<Dog>, // it is wrong, that I can add a Cat! for (Animal animal: animals) { if (animal instanceof Cat) { ((Cat)animal).meow(); } if (animal instanceof Dog) { ((Dog)animal).woof(); } } } } This example compile without errors, and output is: woof woof meow But how can I add in list of Dog a Cat? And how the Cat is casted to Dog? I use: java version "1.6.0_24". OpenJDK Runtime Environment (IcedTea6 1.11.1) (6b24-1.11.1-4ubuntu3)
Tags (comma-separated)
Save Edits
Cancel