Search code examples
javalistgenericsgeneric-programminggeneric-collections

Cannot pass Object which extend of a abstract one into a Method with the abstract Object as Parameter


Here's the code of the method:

public void setupList(ArrayList<AnyAbstractObject> list)
{
     //Here´s the Code stuff. This Method is in the Class: AlphabeticList
}

And I tried to call this method with:

setUpList(new ArrayList<THEObject>);

The Code of THEObject:

public class THEObject extends AnyAbstractObject{//Lalala}

When I'm trying to run this program the console prints this:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method setupList(AnyAbstractObject[]) in the type AlphabeticList is not applicable for the arguments (AlphabeticList)

at Test.Tester.main(Tester.java:22)

What is the issue here?


Solution

  • An ArrayList<THEObject> is not an ArrayList<AnyAbstractObject>, even though an THEObject is an AnyAbstractObject. Here's the catch:

    Every cat is an animal. Is every "room full of cats" a "room full of animals"?

    At first, it seems so. But it isn't. There are stuff you can definitely do with one, but not with the other. For instance, you can take a random individual from a "room full of cats" and cuddle it. But this isn't something you can safely do with a "room full of animals" (beware the bugs, alligators, etc...)

    In Java, we would have the class hierarchy public class Cat extends Animal. And "do stuff with" is to apply a method.

    While you know every individual element you take from an ArrayList<Cat> is a Cat:

     ArrayList<Cat> roomFullOfCats = getKittens();
     Cat tom = roomFullOfCats.get(42);
    

    you can't expect that an individual element you take from an ArrayList<Animal> is a Cat

     ArrayList<Animal> roomFullOfAnimals = getAnimals();
     Animal jerry = roomFullOfAnimals.get(0); // <-- perfectly legal
     Cat tom = roomFullOfAnimals.get(42); //  <-- fails
    

    These are the slippers slopers of Generic Programming, and the Java Tutorial chapter on Generic Programming covers them elegantly.