views:

90

answers:

3

So I have 3 classes.

Abstract class A 

Class B extends class A

independent Class C

In class D that contains the main method, I create a list of instances of class B

List<B> b =  methodCall(); // the method returns a list of instances of class B

Now in class C I have one method that is common to both A and B, and hence I don't want to duplicate it. I want to have one method that takes as input an instance of class A, as follows:

public void someMethod(List<A> a)

However, when I do:

C c = new C();
c.someMethod(b);

I get an error that some-method is not applicable for the argument List<B>, instead it's expecting to get List<A>.

Is there a good way to fix this problem? Many thanks!

+3  A: 
public void someMethod(List<? extends A> a){ //...
Mark Peters
Well, the question keeps getting edited so now I don't know if the poster was trying to use generics or not.
Mark Peters
Edit conflict methinks.
Vivin Paliath
+8  A: 

If you have a method which expects List<A>, and a class B extends A, and you want to pass this method a List<B>, then you should declare the method as:

public void someMethod(List<? extends A> list)

This allows the list passed to the method to be a List of A or anything that extends B.

Note though that you will not be able to tell the exact type of ? passed into the method.

Also, if you have duplicated methods between two classes, that's probably a sign that something is off with your design.

matt b
Thanks a lot! it solved my problem. Didn't know about this option.
Then go ahead and accept the answer.
Mark Peters
+1  A: 

In your method signature you have List<A> a which means it only accepts a list of objects of type A. What you need is something that accepts a list of A and any subtype of A (or a family of subtypes of A).

What you need is this:

public void someMethod(List<? extends A> list) {
  ...
}
Vivin Paliath