将Java接口方法签名声明为final和non-final有什么区别
在 Java 接口中将方法签名声明为最终和非最终有什么区别?
int setName(String name);
int setName(final String name);
what difference does it make in a Java Interface to declare the method signature as final and non-final?
int setName(String name);
int setName(final String name);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Java 的 第 8.4.1 节语言规范允许将任何方法声明中的参数(包括接口中的参数)声明为最终参数。但是,由于这不会影响方法的 签名,将抽象函数的参数声明为
final
无效。由于接口中的所有方法都是隐式抽象,两种变体是等效的。Section 8.4.1 of the Java Language specification allows the parameters in any method declaration (and that includes the ones in interfaces) to be declared final. However, since this does not influence the method's signature, declaring a parameter of an abstract function as
final
has no effect. Since all methods in an interface are implicitely abstract, both variants are equivalent.我在谷歌上能找到的最完整的答案是这个。
很高兴他们提到了使用匿名内部类的链接,因为它是最终参数的一个强大用例。
问候,
史蒂芬
The most complete answer I could find on google is this one.
It's nice they mention the link with using anonymous inner classes as it's a strong use case for final parameters.
Regards,
Stéphane
一些偶然的差异
IDE 可以将其用作提示。例如,当您让 IDE 自动生成已实现的方法时,默认情况下它会以相同的方式将参数设为
final
,即使这些参数名称不属于参数名称的一部分,也会重复使用相同的参数名称。签名也可以。修饰符
final
可通过反射获得,并且可以由框架用于某些隐含目的。A couple of incidental differences
It can be used by the IDE as a hint. e.g. when you get the IDE to auto-generate your implemented methods, it will make the parameters
final
by default in the same way it will re-use the same parameter names even though these are not part of the signature either.the modifier
final
is available via reflection and could be used by a framework for some implied purpose.