有:
public <T extends Foo> int(T a, T b) { }
Run Code Online (Sandbox Code Playgroud)
允许我在aand 中传入不同的类型b,如果两者都实现了Foo接口。
我认为这会更好地表述为:
public <T extends Foo, U extends Foo> int(T a, U b) { }
Run Code Online (Sandbox Code Playgroud)
我的问题是:有没有办法实现第一个签名(a 和 b 是相同的类型并且都实现了Foo接口)?
下面的代码有点难看但是有效。
public class Main {
static class Foo {}
static class Bar extends Foo {}
static class Baz extends Foo {}
static <T extends Foo, S extends T> void foo(T a, S b) { }
public static void main(String []args) {
foo(new Foo(), new Foo()); // Compiles fine
foo(new Bar(), new Bar()); // Compiles fine
foo(new Bar(), new Baz()); // Compiler error Baz doesn't extend Bar
}
}
Run Code Online (Sandbox Code Playgroud)
这与您想要的有点不同,因为它允许第二个参数对第一个参数进行子类化。我认为这是可以的,因为它S是 a,T所以它应该能够在 aT所做的任何地方工作。