Java bounded parameters in general methods

I tested finite parameters through generic methods and found some strange behavior

Imagine that Class1 and class2 have two classes that extend from baseClass Class2 implements an interface

In Class1, I have a method that can return an instance of class2 in the following ways:

public class Class2 extends BaseClass implements Interface {

    @Override
    public void method() {
        System.out.println("test"); //$NON-NLS-1$
    }
}

public class Class1 extends BaseClass {

    public <T extends BaseClass & Interface> T getTwo() {
        return new Class2();
        // Error: Type mismatch: cannot convert from Class2 to T
    }

    public static void main(String[] args) {
        Interface two = new Class1().getTwo();
        // Error: Bound mismatch: The generic method getTwo() of type Class1 is
        // not applicable for the arguments (). The inferred type Interface is
        // not a valid substitute for the bounded parameter <T extends BaseClass
        // & Interface>
        System.out.println(two);
    }
}

Solution

The first compilation error occurs because the type parameters of the method declaration are specified by the caller, not the method implementation in other words

class Class3 extends BaseClass implements Interface { ... }

A caller can write

Class3 c3 = new Class1().<Class3>getTwo();

But the method implementation returns a class2, which is not a subtype of T = class3

The second compilation error occurs because the type parameter not explicitly specified by the caller is inferred from the type of method parameter and method return value assigned to the variable This inference failed here The common solution recommended by the Java language specification is to specify type parameters explicitly in this case (type inference is for the convenience of simple cases; it is not intended to cover all cases)

As for how to correctly declare parameters of this type, I need to know what you are trying to accomplish with these declarations

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>