0

I'm not quite sure how to effectively explain my problem, but I'll try my best:

I have an interface. I want to be able to take a collection of that interface as a parameter in some method. Now, if I have a more specific collection that implements that interface, it doesn't work. Here is an example of what I am talking about:

public class Example
{
    public void example()
    {
        List<ExampleImplementation> list = new ArrayList<ExampleImplementation>();
        exampleMethod(list);//This gives the error
        ExampleImplementation example = new ExampleImplementation();
        exampleMethod(example);//This works fine
    }
    public void exampleMethod(List<ExampleInterface> arg)
    {
        
    }
    public void exampleMethod(ExampleInterface arg)
    {
        
    }
    
    public class ExampleImplementation implements ExampleInterface
    {
        
    }
    public interface ExampleInterface
    {
        
    }
}

The first exampleMethod that uses list returns an error "The method exampleMethod(List<Example.ExampleInterface>) in the type Example is not applicable for the arguments (List<Example.ExampleImplementation>)" even though ExampleImplementation is obviously an ExampleInterface. The only logical thing that I can come up with right now is to make specific polymorphisms for collections of each specific implementation. Is there another way, if not why doesn't this work?

ReBuff
  • 27
  • 6

0 Answers0