Java 通用接口与通用方法,以及何时使用它们 [英] Java Generic Interface vs Generic Methods, and when to use one

查看:24
本文介绍了Java 通用接口与通用方法,以及何时使用它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,除了语法上的差异,什么时候可以在接受泛型参数的方法上使用泛型接口?

I was wondering, aside from syntactic difference, when would one use a generic interface over a method that accepts a generic parameter?

public interface Flight<T>{
   void fly(T obj);
}

结束

public interface Flight{
    void <T> fly(T obj);
}

推荐答案

如果你声明一个通用的方法,你总是让调用者决定,使用哪种类型的参数对于类型参数.方法的实现必须能够处理所有可能的类型参数(它甚至没有办法请求实际的类型参数).

If you declare a generic method, you always let the caller decide, which type arguments to use for the type parameters. The implementation of the method must be able to deal with all possible types arguments (and it doesn’t even have a way to ask for the actual type arguments).

也就是说,像 <T> 这样的方法.void fly(T obj); 声明调用者可以对 T 使用任何类型,而实现唯一可以依赖的是 T 的实际类型> 将可分配给 Object(就像 已声明).

That said, a method like <T> void fly(T obj); states that the caller may use any type for T while the only thing the implementation can rely on is that the actual type for T will be assignable to Object (like if <T extends Object> had been declared).

所以在这个特定的例子中,它与声明 void fly(Object obj); 没有什么不同,它也允许任意对象.

So in this specific example, it’s not different to the declaration void fly(Object obj);, which also allows arbitrary objects.

相反,interface 上的类型参数是契约的一部分,可以由实现指定或限制代码>接口:

In contrast, a type parameter on an interface is part of the contract and may be specified or restricted by an implementation of the interface:

public interface Flight<T>{
   void fly(T obj);
}

允许像

public class X implements Flight<String> {
   public void fly(String obj) {
   }
}

在实现端修复T的类型.或者

fixing the type of T on the implementation side. Or

public class NumberFlight<N extends Number> implements Flight<N> {
   public void fly(N obj) {
   }
}

仍然是通用的,但限制类型.

being still generic but restricting the type.

interface 本身是另一个方法签名的一部分时,interface 的签名也很重要,例如

The signature of an interface is also important when the interface itself is a part of another method signature, e.g.

public void foo(Flight<? super String> f) {
    f.fly("some string value");
}

这里,您传递给 fooFlight 实现必须能够使用 String 值,因此 Flight<String>FlightFlight 就足够了,但不是 Flight.声明这样的契约需要 interface 上的类型参数,而不是 interface 的方法.

here, the Flight implementation, which you pass to foo, must be capable of consuming a String value, so Flight<String> or Flight<CharSequence> or Flight<Object> are sufficient, but not Flight<Integer>. Declaring such a contract requires type parameters on the interface, not at the interface’s methods.

这篇关于Java 通用接口与通用方法,以及何时使用它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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