![](/img/trans.png)
[英]interface variables are final and static by default and methods are public and abstract
[英]default methods in interface but only static final fields
我知道 Inteface 中的所有字段都是隐式static 和 final 。 这在 Java 8 之前是有意义的。
但是随着默认方法的引入,接口也具有抽象类的所有功能。 因此非静态和非最终字段也是必要的。
但是当我尝试正常声明一个字段时,它默认变为 static 和 final 。
有没有办法在 Java 8 中的 Interface 中声明非静态和非 final 字段。
还是我在这里完全误解了什么???
Java 接口中的所有字段都是public static final
。
即使添加了默认方法,在接口中引入可变字段仍然没有任何意义。
由于接口演变的原因,添加了默认方法。 您可以向接口添加新的默认方法,但只有在实现使用接口中已定义的方法时才有意义:
public interface DefaultMethods {
public int getValue();
public default int getValueIncremented() {
if (UtilityMethod.helper()) { // never executed, just to demonstrate possibilities
"string".charAt(0); // does nothing, just to show you can call instance methods
return 0;
}
return 1 + getValue();
}
public static class UtilityMethod {
public static boolean helper() {
return false;
}
}
}
我强烈不建议这样做。 改用抽象类。 但是如果你真的需要它,你可以用一些包装类来做一些解决方法。 下面是一个例子:
public interface TestInterface {
StringBuilder best = new StringBuilder();
default void test() {
best.append("ok");
System.out.print(best.toString());
}
}
否 - 不幸的是,在 Java 8 中,接口中不能没有公共静态最终字段。
但我希望将来这会被添加到语言中。
Scala 允许使用非静态字段的接口,这为代码重用和组合开辟了比 Java 8 中更多的可能性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.