簡體   English   中英

使用接口(由多個類實現)的方法參考

[英]Method Reference Using An Interface (Implemented By More Than One Class) As A Type

public interface Intf {
int size();
}

public class Cls1 implements Intf {
public int size() {
// implementation 1
}

public class Cls2 implements Intf {
public int size() {
// implementation 2
}

現在,以下方法引用的是上述兩種實現中的哪一種?

Intf::size // note: using Intf

編譯器將在以上兩個基礎上進行選擇嗎? 還是該方法引用會引發異常?

一般而言,多態性的正常工作方式。

也就是說,如果您擁有一個intf1 someObject ,您可以調用someObject.instanceMethodName()並使用它。

對於方法引用,這與任何其他類型的方法調用沒有什么不同。

萬一您描述了,將不會選擇任何實現(這是一件好事,編譯器和解釋器都無法做出決定),因為

Intf::size

實際上是

Function<? extends Intf, Integer>

要么

ObjToIntFunction<? extends Intf> // considering that return type is primitive int

這意味着您創建的lambda接受可分配給Intf類型的單個實例並返回整數。

現在,如果你說

new Cls1()::size

然后您將生成一個IntSupplierSupplier<Integer> ,以更合適的為准。 供應商是不接受任何參數的方法,需要您自己選擇實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM