java – 接口中的默认方法,但只有静态最终字段

我知道Inteface中的所有字段都是隐式的 static and final.这在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;
        }
    }
}

相关文章

Java中的String是不可变对象 在面向对象及函数编程语言中,不...
String, StringBuffer 和 StringBuilder 可变性 String不可变...
序列化:把对象转换为字节序列的过程称为对象的序列化. 反序...
先说结论,是对象!可以继续往下看 数组是不是对象 什么是对...
为什么浮点数 float 或 double 运算的时候会有精度丢失的风险...
面试题引入 这里引申出一个经典问题,看下面代码 Integer a ...