Cod*_*der 6 java default-method
我知道Inteface 中的所有字段都是隐式静态和最终的.这在Java 8之前就有意义了.
但是随着默认方法的引入,接口也具有抽象类的所有功能.因此,非静态和非最终字段也是必要的.
但是当我尝试正常声明一个字段时,它默认变为静态和最终.
有没有办法在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;
}
}
}
Run Code Online (Sandbox Code Playgroud)