Java 8(预发布)接口成员变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12150240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 (pre-release) interface member variables
提问by McDowell
Are public members variables in Java 8 interfaces a feature or an implementation side-effect/defect?
Java 8 接口中的公共成员变量是功能还是实现副作用/缺陷?
This question pertains to the pre-release Java 8 build lambda-8-b50-linux-x64-26_jul_2012.tar.gz.
此问题与 Java 8 预发布版本lambda-8-b50-linux-x64-26_jul_2012.tar.gz 相关。
Java 8 introduces new features to interfaces in the form of default methods. Casual testing with the JDK8 lambda compiler allows interfaces of this form:
Java 8 以默认方法的形式为接口引入了新特性。使用 JDK8 lambda 编译器进行的随意测试允许使用以下形式的接口:
public interface Foo {
public int foo = 0;
int foo() default { return foo; }
}
Sample implementing type:
示例实现类型:
public class FooImpl implements Foo {
public int foo = 1;
}
This code follows the standard conventions for variable shadowing:
此代码遵循变量阴影的标准约定:
Foo f = new FooImpl();
System.out.println(f.foo());
System.out.println(f.foo);
System.out.println(new FooImpl().foo);
Output:
输出:
0
0
1
The documentation (JSR 335: Lambda Expressions for the Java? Programming Language Version 0.5.1) doesn't mention member variables. I'm inclined to think the compiler is being too tolerant but perhaps I've missed something.
文档(JSR 335:Java 的 Lambda 表达式?编程语言版本 0.5.1)没有提到成员变量。我倾向于认为编译器太宽容了,但也许我错过了一些东西。
回答by TimK
Public fields in interfaces are not a new features in Java 8. If you remember that they are implicitly static and final, the results you are seeing make perfect sense.
接口中的公共字段不是 Java 8 中的新特性。如果您还记得它们是隐式静态和最终的,那么您看到的结果就非常有意义。