[英]How Inheritance works in Java with method reference operator
界面
public interface InterfaceOne {
void start();
void stop();
}
主班
public class MainProg {
public static void main(String [] args){
new ServiceA().start();
}
}
服務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);
}
}
服務B
public class ServiceB extends ServiceC{
int count;
protected ServiceB(int num){
this.count = num;
}
}
服務C
public class ServiceC implements InterfaceOne{
@Override
public void start() {
System.out.println("Starting..");
}
@Override
public void stop() {
System.out.println("Stopping..");
}
}
在這里,我從主類調用 ServiceA 的方法,該方法使用方法引用運算符在內部調用 serviceB 的方法。 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());
}
}
在這里,我知道這個程序是如何使用 lambda 函數工作的,但想了解它是如何與方法引用運算符一起工作的
worker.forEach(InterfaceOne::start);
這個程序的輸出是
Starting..
Starting..
你寫了:
worker.forEach(InterfaceOne::start);
這將為工作列表的每個元素調用 start 方法。 不管是在ServiceA的方法范圍內調用,worker列表的元素都是ServiceB的,繼承了ServiceC的start
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.