2

Possible Duplicate:
Is List<Dog> a subclass of List<Animal>? Why aren't Java's generics implicitly polymorphic?

I have this code:

ArrayList<A> objects = new ArrayList<A>();

objects.add(new B());

where B is a child class o A. It gives me a compile time error like so:

The method add(A) in the type ArrayList is not applicable for the arguments (B)

Community
  • 1
  • 1
rdelfin
  • 819
  • 2
  • 13
  • 31
  • 1
    @SLaks: It's really not relevant in this case. Why do you need the classes? – wchargin Aug 26 '12 at 20:16
  • Ignore that (my) close-vote. I had the question mixed up. –  Aug 26 '12 at 20:19
  • I'm going to check more carefully. I can't find the problem yet but this worked well before – rdelfin Aug 26 '12 at 20:22
  • @WChargin Why is it not relevant? The OP has some problems with the A <-> B relationship. We need to sort it out and if he gives us more info that will be helpful. – maba Aug 26 '12 at 20:25
  • 1
    It's irrelevant because all you need is to know which class extends which. The implementation or rest of the structure is not important for polymorphism – rdelfin Aug 26 '12 at 20:27
  • Found the error. I was importing a class with the same name but in a different place – rdelfin Aug 26 '12 at 20:32
  • So if you would have shown us the code we could have seen that. Now everybody was guessing that you had mixed up the `A` and `B` relationship which you obviously had not. – maba Aug 26 '12 at 20:35
  • The problem was in the imports – rdelfin Aug 26 '12 at 20:53

1 Answers1

10

This compiles and runs fine:

import java.util.ArrayList;

class A {
}

class B extends A {
}

class Test {
    public static void main(String[] args) {
        ArrayList<A> arraylist = new ArrayList<A>();
        arraylist.add(new B());
    }
}

Have another look at your code. Perhaps you got it backwards and A extends B?

Niko
  • 26,516
  • 9
  • 93
  • 110
aioobe
  • 413,195
  • 112
  • 811
  • 826