简体   繁体   English

继承如何在 Java 中使用方法引用运算符工作

[英]How Inheritance works in Java with method reference operator

Interface界面

public interface InterfaceOne {
    void start();
    void stop();
}

Main Class主班

public class MainProg {
    public static void main(String [] args){
        new ServiceA().start();
    }
}

ServiceA服务A

import java.util.ArrayList;
import java.util.List;

public class ServiceA implements InterfaceOne{
    private final List<ServiceB> worker = new ArrayList<>();
    public ServiceA(){
        for(int i = 0; i < 2; i++){
            worker.add(new ServiceB(2));
        }
    }

    @Override
    public void start() {
        worker.forEach(InterfaceOne::start);
    }

    @Override
    public void stop() {
        worker.forEach(InterfaceOne::stop);
    }
}

ServiceB服务B

public class ServiceB extends ServiceC{
    int count;
    protected ServiceB(int num){
        this.count = num;
    }
}

ServiceC服务C

public class ServiceC implements InterfaceOne{
    @Override
    public void start() {
        System.out.println("Starting..");
    }

    @Override
    public void stop() {
        System.out.println("Stopping..");
    }
}

Here from the main class, I am calling a method of ServiceA that internally calls to the method of serviceB using the method reference operator.在这里,我从主类调用 ServiceA 的方法,该方法使用方法引用运算符在内部调用 serviceB 的方法。 ServiceA Can be also written like below where instead of using the method reference operator i can use lambda function ServiceA 也可以像下面这样写,而不是使用方法引用运算符,我可以使用 lambda 函数

import java.util.ArrayList;
import java.util.List;

public class ServiceA implements InterfaceOne{
    private final List<ServiceB> worker = new ArrayList<>();
    public ServiceA(){
        for(int i = 0; i < 2; i++){
            worker.add(new ServiceB(2));
        }
    }

    @Override
    public void start() {
        worker.forEach(obj -> obj.start());
    }

    @Override
    public void stop() {
        worker.forEach(obj -> obj.stop());
    }
}

Here I am aware of how this program is working using lambda function, but want to understand how it is working with the method reference operator在这里,我知道这个程序是如何使用 lambda 函数工作的,但想了解它是如何与方法引用运算符一起工作的

worker.forEach(InterfaceOne::start);

The output of this program is这个程序的输出是

Starting..
Starting..

You wrote:你写了:

worker.forEach(InterfaceOne::start);

This calls the start method for every element of the worker list.这将为工作列表的每个元素调用 start 方法。 It does not matter if it's called in the scope of a method of ServiceA, the elements of the worker list are ServiceB's, which inherit the start method of ServiceC.不管是在ServiceA的方法范围内调用,worker列表的元素都是ServiceB的,继承了ServiceC的start方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM