Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error using an Interface as a return type [Java]

Tags:

java

interface

I've these two Java interfaces:

the first one is:

public abstract interface A {

}

and the second one is:

public abstract interface B {
    public abstract Set<A> methodName();
}

Then, I've implemented these two interfaces as:

public class AImpl implements A {

}

and:

public class BImpl implements B {
    private Set<AImpl> p;  

    public Set<A> methodName() {
        return this.p;
    }
}

I don't understand why I obtain the following error about the implementation of methodName():

Type mismatch: cannot convert from Set<AImpl> to Set<A>

Thank you very much.

like image 995
user2467899 Avatar asked Feb 11 '23 04:02

user2467899


1 Answers

Set<AImpl> is not exactly the same what Set<A>, you cannot convert it. You can:

  • declare p as Set<A>
  • declare p as Set<? extends A>
  • return Set<AImpl> in methodName()

More details: if AImpl implements/extends A then List<AImpl> does not implement/extend List<A>. List<? extends A> means that this is the list of something that extends/implements A.

Look at Wildcards and subtyping in Java Tutorial

like image 109
Patryk Dobrowolski Avatar answered Feb 13 '23 20:02

Patryk Dobrowolski