April 4, 2011

Generics Example with wildcards


package info.icontraining.collections;


import java.util.*;


public class Animal {


   public static void main(String args[]) {


List<Cat> listCats = new ArrayList<Cat>();
List<Dog> listDogs = new ArrayList<Dog>();

listCats.add(new Cat());
listCats.add(new Cat());

listDogs.add(new Dog());
listDogs.add(new Dog());
listDogs.add(new Dog());

m1(listCats);
m1(listDogs);
   }

   public void eat() {

   }

   public static void m1(List<? extends Animal> l) {
// cannot add any new objects to 
// list in this method

for(Animal i : l) {
i.eat();
}
   }
}


class Dog extends Animal {
    public void eat() {
System.out.println("Dog");
    }
}


class Cat extends Animal {
    public void eat() {
System.out.println("Cat");
    }
}

No comments:

Post a Comment