Building Typical Types in Java

I get a type mismatch error in a situation that I would not expect.

public interface I {}

public abstract class C {}

public class A extends C implements I {}

public class B extends C implements I {}

public class Foo {

    public <T extends C & I> T getComposition(String selector) {
        switch (selector) {
            case "a": return new A(); // type-mismatch!
            case "b": return new B(); // type-mismatch!
        }
    }

}

Why A, which is both C, and Icannot return as T?

+4
source share
2 answers

The designation <T extends C & I>means that it Tis a type parameter. This means that when someone calls a function, they must indicate this type. The only limitation is that the type extends Cand I. Ais one of these types, but I could create a new class that also extends Cand I. Like this example:

class B extends C implements I {}

Foo foo = new Foo();
B b = foo.<B>getComposition();

, , A B.

A, A. :

public class Foo {
    public A getComposition() {
        return new A();
    }
}
+4

, . A B - T, . T A B . . D D, A. , D T. , T A, , D A. , D A.

+1

Source: https://habr.com/ru/post/1669356/


All Articles