Rafael T
Rafael T

Reputation: 15689

Why this generic return type of a method is not valid

I don't get it. In java I'm allowed to declare an interface as a return type of a method, like:

public List<String> get(){
    return new ArrayList<String>();
}

if I now have an interface lets say I and a class C implementing it, why I'm not allowed to define like this:

public List<I> get(){
    return new ArrayList<C>();
}

I know the solution to create an ArrayList<I> and add C to it, but I'm wondering why I'm not allowed to declare it like the one above. I thought that every C is also a I though it should be no problem.

Upvotes: 2

Views: 212

Answers (2)

Lucero
Lucero

Reputation: 60256

You are running into an issue with co- and contravariance. To put it short: your List<I> interface has also a method Add, which expects an instance of I, but not every I will in fact be implemented by C, as any other class may also implement I. Therefore you'll end up with typecasting issues.

Upvotes: 5

Lukas Eder
Lukas Eder

Reputation: 221115

You cannot do this because List<I> and List<C> are incompatible types.

You can do this, however

public List<? extends I> get(){
    return new ArrayList<C>();
}

Upvotes: 10

Related Questions