fork download
  1. import java.util.*;
  2. class Ideone
  3. {
  4. public static void main (String[] args) throws java.lang.Exception
  5. {
  6. List<Dog> dogs = new ArrayList<>();
  7. dogs.add(new Dog());
  8. dogs.add(new Dog());
  9.  
  10. // fun(dogs); // not allowed
  11.  
  12. List<Animal> animals = new ArrayList<>();
  13. animals.add(new Animal());
  14. animals.add(new Animal());
  15.  
  16. fun(animals);
  17.  
  18. fun2(dogs);
  19. fun2(animals);
  20.  
  21. fun3(animals);
  22. fun3(dogs);
  23. }
  24.  
  25. static void fun(List<Animal> animals){
  26. for(Animal a : animals){
  27. a.eat();
  28. }
  29. }
  30.  
  31. static void fun2(List<?> values){ // can only be read
  32. for(Object obj : values){
  33. System.out.println(obj.getClass());
  34. }
  35.  
  36. // values.add(new Animal()); // not allowed to modify in wildcard generics
  37. }
  38.  
  39. static void fun3(List<? extends Animal> values){ // wildcards with upper bound
  40. for(Animal a : values){
  41. a.eat();
  42. }
  43. }
  44. }
  45.  
  46. class Animal {
  47. void eat(){
  48. System.out.println("Animal eats");
  49. }
  50. }
  51.  
  52. class Dog extends Animal {
  53. void eat(){
  54. System.out.println("Dog eats");
  55. }
  56. void bark(){
  57. System.out.println("Dogs can bark");
  58. }
  59. }
Success #stdin #stdout 0.07s 52548KB
stdin
Standard input is empty
stdout
Animal eats
Animal eats
class Dog
class Dog
class Animal
class Animal
Animal eats
Animal eats
Dog eats
Dog eats