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..
private final List<ServiceB> workerlist, which as you can see contains Objects of typeServiceBand those calls onServiceBare what are generating the output. That you for some reason decided to haveServiceB extends ServiceCprobably just added to your confusion. ( If you name classes A, B, and C you usually expect those names to mean that B extends A and C extends B, not what you decided to do)workerslist and calls the methodstarton each one. This was btw already explained in the answer you got below.worker.forEach(obj -> obj.start());andworker.forEach(InterfaceOne::start);above two lines creates same output, here i want to understand more aboutworker.forEach(InterfaceOne::start);