vs可以调用java接口吗,Java通用接口vs通用方法,以及何时使用它

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{

void fly(T obj);

}

over

public interface Flight{

void 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 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 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 the interface:

public interface Flight{

void fly(T obj);

}

allows implementations like

public class X implements Flight {

public void fly(String obj) {

}

}

fixing the type of T on the implementation side. Or

public class NumberFlight implements Flight {

public void fly(N obj) {

}

}

being still generic but restricting the type.

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");

}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值