泛型参数扩展了Java方法的另一个参数 [英] Generics parameter extends another parameter on java method

查看:82
本文介绍了泛型参数扩展了Java方法的另一个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,也许这是一个愚蠢的问题,但我找不到答案.

Sorry, maybe it is a silly question, but I can't find answer.

方法上有两个泛型参数,可以扩展另一个吗?

Two generics parameters on a method, could one extends another?

public class A {
}

public class B extends A {
}

public class C {
}

public class Foo {

    public static <R extends A> void f1 (A t, R r){
    }

    // T and R are generics parameter, R bounds on T
    public static <T, R extends T > void f2(T t, R r) {
    }

    public static void main(String[] args) {

        A a = new A();
        B b = new B();
        C c = new C();

        Foo.f1(a, b); // no error
        Foo.f1(a, c); // compile error, it's ok

        Foo.f2(a, b); // no error
        Foo.f2(a, c); // no error !  why? 
   }
}

最后一个f2方法调用没有编译错误,但是我认为C不是A的子类,应该会出现编译错误.有帮助吗?

The last f2 method call has no compile error, but I think C is not subclass of A, compile error should be arised. Any help?

推荐答案

因为调用此方法的代码中的类型参数是隐式的,例如,如果Java编译器将TR推断为Object,就可以了,不是吗?但是,如果您明确声明它们,则会引发错误:

Because type parameters in your code where you call the method are implicit and for example if java compiler infers T and R to Object it's fine, isn't it? But if you declare them explicit it raises an error:

 Foo.<A, C>f2(a, c); //error as you wished
 Foo.<Object, Object>f2(a, c); //no errors and it's ok, isn't it?

这篇关于泛型参数扩展了Java方法的另一个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆