Advertisement
Guest User

Untitled

a guest
Apr 21st, 2014
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. public void foo() {
  2. Cat[] cats = {new Cat(), new Cat()};
  3. addAnimals(cats);
  4. }
  5.  
  6. public void addAnimal(Animal[] animals) {
  7. animals[0] = new Dog(); // No compile time error. But ArrayStoreException
  8. // at runtime as the JVM knows the type of animals.
  9. }
  10.  
  11. interface Species {
  12.  
  13. }
  14.  
  15. class Animal implements Species {
  16.  
  17. }
  18.  
  19. class Cat extends Animal {
  20.  
  21. }
  22.  
  23. class Dog extends Animal {
  24.  
  25. }
  26.  
  27. class Plant implements Species {
  28.  
  29. }
  30.  
  31. class Tree extends Plant {
  32.  
  33. }
  34.  
  35. public void test() {
  36. System.out.println("Hello");
  37. List<Animal> animals = new ArrayList<>();
  38. animals.add(new Cat());
  39. animals.add(new Dog());
  40. // Not allowed.
  41. //animals.add(new Tree());
  42.  
  43. // The old way.
  44. List beasts = new ArrayList();
  45. beasts.add(new Cat());
  46. beasts.add(new Dog());
  47. // Allowed - only caught at run time and difficult to find.
  48. beasts.add(new Tree());
  49.  
  50. // The interface way.
  51. List<Species> living = new ArrayList();
  52. living.add(new Cat());
  53. living.add(new Dog());
  54. // Allowed.
  55. living.add(new Tree());
  56.  
  57. }
  58.  
  59. List<Cat> cats = new ArrayList<Cat>();
  60. List<Animal> animals = cats;
  61. animals.add(new Dog());
  62.  
  63. for (Cat c : cats) { ...}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement