Monday, February 16, 2015

Passing Arraylist of sub class type to a function

Suppose we have Animal class and Dog class is subclass of Animal class. To pass the arraylist of Dog which is subclass of Animal to a function Display (which takes ArrayList of Animal), we have to use Type of ArrayList. ArrayList is checked in compile time. So, when we use type, then its tied to a specific type, You cant add any new element in the function.

 private <T extends Animal> void Display(List<T> animals)


Animal.java

public class Animal {

    public void eat()
    {
        System.out.println("Animal eating");
    }

    public static void main(String[] args)
    {

        List<Dog> dogs=new ArrayList<Dog>();
        dogs.add(new Dog());
        dogs.add(new Dog());
        new Animal().Display(dogs);


    }


    private <T extends Animal> void Display(List<T> animals) {
        for(T a:animals)
        {

            a.eat();
        }
    }
}

Dog.java

public class Dog extends Animal{

    public void eat()
    {
        System.out.println("Dog eating");
    }
}


No comments:

Post a Comment