为什么Interfaces中没有静态方法,但是静态字段和内部类可以吗? [预Java8] [英] Why no static methods in Interfaces, but static fields and inner classes OK? [pre-Java8]

查看:150
本文介绍了为什么Interfaces中没有静态方法,但是静态字段和内部类可以吗? [预Java8]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有一些问题,为什么你不能在接口中定义静态方法,但它们都没有解决基本的不一致性:为什么你可以在接口中定义静态字段和静态内部类型,而不是静态方法?

There have been a few questions asked here about why you can't define static methods within interfaces, but none of them address a basic inconsistency: why can you define static fields and static inner types within an interface, but not static methods?

静态内部类型可能不是一个公平的比较,因为这只是产生新类的语法糖,但为什么是字段而不是方法?

Static inner types perhaps aren't a fair comparison, since that's just syntactic sugar that generates a new class, but why fields but not methods?

接口中静态方法的一个参数是它破坏了JVM使用的虚拟表解析策略,但不应该同样适用于静态字段,即编译器可以内联它吗?

An argument against static methods within interfaces is that it breaks the virtual table resolution strategy used by the JVM, but shouldn't that apply equally to static fields, i.e. the compiler can just inline it?

一致性是我想要的,Java应该支持接口中没有任何形式的静态,或者它应该是一致的并允许它们。

Consistency is what I desire, and Java should have either supported no statics of any form within an interface, or it should be consistent and allow them.

推荐答案

正式提案已经允许在Java 7中的接口中使用静态方法。该提议是在项目硬币

An official proposal has been made to allow static methods in interfaces in Java 7. This proposal is being made under Project Coin.

我个人认为这是一个好主意。实施中没有技术上的困难,这是一个非常合乎逻辑的合理的事情。 Project Coin中有几个提议我希望永远不会成为Java语言的一部分,但这可以清理很多API。例如, 集合类具有静态方法,用于操作任何 List 实现;这些可以包含在列表界面中。

My personal opinion is that it's a great idea. There is no technical difficulty in implementation, and it's a very logical, reasonable thing to do. There are several proposals in Project Coin that I hope will never become part of the Java language, but this is one that could clean up a lot of APIs. For example, the Collections class has static methods for manipulating any List implementation; those could be included in the List interface.

更新: Java Posse播客#234, Joe D'arcy简要地提到了这个提议,说这是复杂的,可能不会在Project Coin下进行。

Update: In the Java Posse Podcast #234, Joe D'arcy mentioned the proposal briefly, saying that it was "complex" and probably would not make it in under Project Coin.

更新:虽然它们没有进入Java 7的Project Coin,但Java 8确实支持接口中的静态函数。

Update: While they didn't make it into Project Coin for Java 7, Java 8 does support static functions in interfaces.

这篇关于为什么Interfaces中没有静态方法,但是静态字段和内部类可以吗? [预Java8]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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