Java通用接口vs通用方法,以及何时使用它 [英] Java Generic Interface vs Generic Methods, and when to use one
问题描述
我想知道,除了语法上的差异之外,什么时候使用泛型接口来接受一个泛型参数?
public interface Flight< T> {
void fly(T obj);
}
超过
public interface Flight {
void< T>飞(T obj);
em> method ,你总是让 caller 决定哪些类型参数用于类型参数。该方法的实现必须能够处理所有可能的类型参数(甚至没有办法请求实际的类型参数)。
说,像< T> void fly(T obj);
声明调用者可以为 T
使用任何类型,而实现可以依赖的唯一东西是实际类型如果< T extends Object>
已被声明)。
因此,在这个特定的例子中,它与声明 void fly(Object obj) ;
,它也允许任意对象。
相比之下, code>
是合约的一部分,可以通过接口
的实现指定或限制:
public interface Flight< T> {
也很重要,例如
void fly(T obj);
$ b $ p
$ b允许像
public class X实现了Flight< String> {
public void fly(String obj){
}
}
修复实现端的
T
类型。或者
public class NumberFlight< N extends Number>实现Flight< N> {
public void fly(N obj){
}
}
<
<$ c的签名当
接口
本身是另一个方法签名的一部分时,$ c> interfacepublic void foo(Flight< ;? super String> f){
f.fly(some string value);
}
这里,
Flight
实现,您传递给foo
的实现必须能够使用String
值,所以Flight< String>
或Flight< CharSequence>
或Flight<>
,但不是Flight< Integer>
。声明这样一个合约需要在接口
上的类型参数,而不是在接口
的方法中。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); }
over
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).
That said, a method like
<T> void fly(T obj);
states that the caller may use any type forT
while the only thing the implementation can rely on is that the actual type forT
will be assignable toObject
(like if<T extends Object>
had been declared).So in this specific example, it’s not different to the declaration
void fly(Object obj);
, which also allows arbitrary objects.In contrast, a type parameter on an
interface
is part of the contract and may be specified or restricted by an implementation of theinterface
:public interface Flight<T>{ void fly(T obj); }
allows implementations like
public class X implements Flight<String> { public void fly(String obj) { } }
fixing the type of
T
on the implementation side. Orpublic class NumberFlight<N extends Number> implements Flight<N> { public void fly(N obj) { } }
being still generic but restricting the type.
The signature of an
interface
is also important when theinterface
itself is a part of another method signature, e.g.public void foo(Flight<? super String> f) { f.fly("some string value"); }
here, the
Flight
implementation, which you pass tofoo
, must be capable of consuming aString
value, soFlight<String>
orFlight<CharSequence>
orFlight<Object>
are sufficient, but notFlight<Integer>
. Declaring such a contract requires type parameters on theinterface
, not at theinterface
’s methods.这篇关于Java通用接口vs通用方法,以及何时使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!