我理解Inteface中的所有字段都是隐式static and final。这在Java 8之前就有意义了。
但是随着默认方法的引入,接口也具有抽象类的所有功能。因此,非静态和非最终字段也是必要的。
但是当我尝试正常声明一个字段时,它默认变为静态和最终。
有没有办法在Java 8中的Interface中声明非静态和非最终字段。
或者我在这里完全误解了什么?
答案 0 :(得分:9)
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;
}
}
}
答案 1 :(得分:3)
否 - 在Java 8中,所有字段都是静态的和最终的,就像以前的Java版本一样。
在界面中包含州(字段)会引发问题,特别是与the diamond problem有关。
另请参阅this entry,其中阐明了行为与状态继承之间的区别。
答案 2 :(得分:0)
我强烈建议您不要这样做。请改用抽象类。但是,如果您确实需要它,可以使用一些包装器类来解决问题。这是一个示例:
public interface TestInterface {
StringBuilder best = new StringBuilder();
default void test() {
best.append("ok");
System.out.print(best.toString());
}
}
答案 3 :(得分:-1)
否 - 在java 8中,您不能在接口中使用字段。
但我希望将来这会被添加到语言中。
Scala允许与字段接口,这为代码重用和组合提供了比Java 8中更多的可能性