Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public void foo() {
- Cat[] cats = {new Cat(), new Cat()};
- addAnimals(cats);
- }
- public void addAnimal(Animal[] animals) {
- animals[0] = new Dog(); // No compile time error. But ArrayStoreException
- // at runtime as the JVM knows the type of animals.
- }
- interface Species {
- }
- class Animal implements Species {
- }
- class Cat extends Animal {
- }
- class Dog extends Animal {
- }
- class Plant implements Species {
- }
- class Tree extends Plant {
- }
- public void test() {
- System.out.println("Hello");
- List<Animal> animals = new ArrayList<>();
- animals.add(new Cat());
- animals.add(new Dog());
- // Not allowed.
- //animals.add(new Tree());
- // The old way.
- List beasts = new ArrayList();
- beasts.add(new Cat());
- beasts.add(new Dog());
- // Allowed - only caught at run time and difficult to find.
- beasts.add(new Tree());
- // The interface way.
- List<Species> living = new ArrayList();
- living.add(new Cat());
- living.add(new Dog());
- // Allowed.
- living.add(new Tree());
- }
- List<Cat> cats = new ArrayList<Cat>();
- List<Animal> animals = cats;
- animals.add(new Dog());
- for (Cat c : cats) { ...}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement