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

查看:20
本文介绍了为什么接口中没有静态方法,但静态字段和内部类可以?[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.

推荐答案

An 官方提议允许Java 7接口中的静态方法.这个提议是在Project Coin.

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 的提案.例如,Collections 类具有用于操作任何 List 实现的静态方法;那些可以包含在 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 Podcast #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.

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

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