0

I am getting following error when I execute the code mentioned below:

TestGenerics1.java:40: error: cannot find symbol
                              arr.get(i).eat();
                                        ^
symbol:   method eat()
location: class Object
1 error

The issue I am facing is reproduced with the help of following sample code:

import java.util.*;

abstract class Animal
{
    void eat() { System.out.println("animal eating"); }
}

class Dog extends Animal
{
    void bark() { }
}

class Cat extends Animal
{
    void meow() { }
}

class RedCat extends Cat { }

public class TestGenerics1
{
    public static void main(String[] args)
    {
        new TestGenerics1().go();
    }

    public void go()
    {
        List<Cat> arrAnimals = new ArrayList<Cat>(Arrays.asList(new RedCat(), new Cat()));

        takeAnimals(arrAnimals);
    }

    //public static void takeAnimals(List<Cat> arr)
    public static void takeAnimals(List<? super RedCat> arr)
    {
        for(int i=0; i<arr.size(); i++)
        {
            arr.get(i).eat();
        }
    }
}

If I uncomment public static void takeAnimals(List<Cat> arr) and comment out public static void takeAnimals(List<? super RedCat> arr) then it works good.

Why does it not work with public static void takeAnimals(List<? super RedCat> arr) ?

Sachin S
  • 396
  • 8
  • 17

1 Answers1

5

List<? super RedCat> is list of some types which are supertype of RedCat.

The compiler cannot figure out which type is passed and does not guaranteed eat() method exists.

Instead, you should use extends:

List<? extends Cat>
Mạnh Quyết Nguyễn
  • 17,677
  • 1
  • 23
  • 51