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)
?