Home > Blockchain >  How Inheritance works in Java with method reference operator
How Inheritance works in Java with method reference operator

Time:06-13

Interface

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

Main Class

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

ServiceA

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

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

ServiceC

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 Can be also written like below where instead of using the method reference operator i can use lambda function

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

worker.forEach(InterfaceOne::start);

The output of this program is

Starting..
Starting..

CodePudding user response:

You wrote:

worker.forEach(InterfaceOne::start);

This calls the start method for every element of the worker list. 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.

  • Related