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

3
  • 1
    ? super RedCat allows e.g. List<Object> to be passed in. Commented Jun 3, 2018 at 12:39
  • 1
    Possible duplicate of What is PECS (Producer Extends Consumer Super)? Commented Jun 3, 2018 at 12:40
  • Mehotd should be 'takeAnimals(List<? extends Animal> arr)' to solve compile error Commented Jun 3, 2018 at 12:48

1 Answer 1

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> 
Sign up to request clarification or add additional context in comments.

3 Comments

I think it should be List<? extends Animal> since Animal defines method eat().
Good point. But I think wildcard is good in situation where we want to restrict/narrow down type of input list
List<? extends Cat> allows Cat and suptypes of Cat only. In your program, they're Cat and RedCat

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.