如何用Java-8实现继承?

如何用Java-8实现继承?,java-8,Java 8,我有一个带有AddService类的程序,它正在实现IService接口,如下所示: iSeries.java AddService.java 上面的代码编译并运行良好,但只要我使用Java-8提供的双功能更改上面的实现,IDE就会在编译时开始抱怨 iSeries.java AddService.java 知道如何解决错误并使程序运行吗?假设IService是出于某种原因创建的,并且实际实现非常简单,我会编写这样一个非繁琐的实现 public interface IService { i

我有一个带有AddService类的程序,它正在实现IService接口,如下所示:

iSeries.java

AddService.java

上面的代码编译并运行良好,但只要我使用Java-8提供的双功能更改上面的实现,IDE就会在编译时开始抱怨

iSeries.java

AddService.java

知道如何解决错误并使程序运行吗?

假设IService是出于某种原因创建的,并且实际实现非常简单,我会编写这样一个非繁琐的实现

public interface IService {
    int op(int x, int y);
}

public enum OpService implements IService {
    ADD {
        @Override
        public int op(int x, int y) {
            return x + y;
        }
    },
    MINUS {
        @Override
        public int op(int x, int y) {
            return x - y;
        }
    }
}

class A {
    public static void main(String[] args) {
        IntBinaryOperator add = OpService.ADD::op;
        IntBinaryOperator minus = OpService.MINUS::op;

        System.out.println(add.applyAsInt(2, 3));
    }
}
印刷品

5

然而,如果你只想把两个数字加在一起,我就用+

你误解了。假设你有一个像这样的方法

public void someMethod(IService addService) {
    System.out.println(addService.add(2, 4));
}
public void anotherMethod() {
    someMethod((x, y) -> x + y);
}
使用Java8,您现在可以像

public void someMethod(IService addService) {
    System.out.println(addService.add(2, 4));
}
public void anotherMethod() {
    someMethod((x, y) -> x + y);
}
而不是必须正确地实现IService并执行以下操作

public void anotherMethod() {
    someMethod(new AddService());
}
lambda可以作为所有功能接口的实现。双功能接口的存在使得您甚至不必添加IService接口。相反,你可以这样做

public void someMethod2(BiFunction<Integer, Integer, Integer> addService) {
    System.out.println(addService.apply(2, 4));
}

public void anotherMethod() {
    someMethod((x, y) -> x + y);
}

而且它仍然有效。这一次,相同的lamda将被视为双函数,而不是iSeries。Lambda表达式使您能够将代码表示为数据。你可以写:

IService addService = (x, y) -> x + y;
它声明了一个实现IService的变量addService。更好的方法是,摆脱iSeries并使用IntBinaryOperator:


并在本应使用新AddService的位置使用add

add是接口中的一个隐式静态final字段,这里没有继承。Java8不会更改编写类的方式。您可以使用x,y->x+y来代替iSeries实现,尽管此时不需要编写类all@Tom:将add更改为addx,y会产生编译时错误,因为-x无法重新加载,知道如何修复它吗?Java 8中的继承与以前版本中的继承实现方式相同。您发布了一个工作版本,然后,在询问我们为什么更改不起作用之前,请解释您为什么做这些更改以及您想用它们实现什么。双功能充当iSeries设备的替代品。您定义的第二个IService有一个函数add,该函数返回一个BIFUNCTION,这与第一个IService的意图不同。您可能还想使用IntBinaryOperator来避免装箱。真的吗?你是这样写的?声明一个不使用的接口,通过枚举实现它,只是为了从中创建方法引用?首先实现IntBinaryOperator而不是iSeries如何?或者只是为方法引用创建两个静态方法,没有过时的接口和enum?@Holger在这个简单的例子中,我同意您可以删除大部分代码。布赖恩的解决方案就足够了。但是,假设IService是出于某种原因创建的,并且这个示例非常重要,这就是我使用的模式。@Holger如果您只想将两个数字相加,我不会使用lambdas,我会使用+
public void someMethod2(BiFunction<Integer, Integer, Integer> addService) {
    System.out.println(addService.apply(2, 4));
}

public void anotherMethod() {
    someMethod((x, y) -> x + y);
}
IService addService = (x, y) -> x + y;
IntBinaryOperator add = (x, y) -> x + y;
IntBinaryOperator subtract = (x, y) -> x - y;
...