簡體   English   中英

如果我調用一個接口方法,它會從實現類中獲取方法體並執行嗎?

[英]If I call an interface method, will it get the method body from implementation class and execute?

我有一個接口Interface1 我有它的實現Imple implements Interface1 (所有方法都已實現:))。

現在,考慮第三類CheckCall ,我可以在類CheckCall進行調用,如下所述:

Interface1 interface1;
interface1.method();

所有必要的進口都已完成。 請告訴我是否可能,如果不是那么好,如果是,那么告訴我如果我有多個實現類用於同一個接口並且我正在進行相同的調用會發生什么。

好吧,你不能直接在界面上調用方法,但你可以或多或少地做你寫的。

你寫了:

Interface1 interface1;
interface1.method();

如果您這樣做,這將有效:

Interface1 interface1 = new CheckCall();
interface1.method();

然后告訴我如果我有同一個接口的多個impl類並且我正在進行相同的調用會發生什么

嗯,這是關於Java的好處:你所指的問題叫做“鑽石問題”:

http://en.wikipedia.org/wiki/Diamond_problem

它並不存在於Java中,因為Java完全支持多重繼承,但只能通過“多(Java)接口繼承” (*參見注釋)。

因此,在您調用interface1.method()情況下,您要么調用Impl的方法,要么調用CheckCall的方法,並且不存在混淆。

當然,你的代碼工作正常! 您只需使用實際實現(即new Imple())初始化變量interface1

看看這個例子,我使用了你的類名:

public class CheckCall {

    interface Interface1 {
        void method();
    }

    static class Imple implements Interface1 {
        @Override
        public void method() {
            System.out.println("Imple.method1()");
        }
    }

    public static void main(String[] args) {
        Interface1 interface1;
        interface1 = new Imple();
        interface1.method();
    }

}

是的,但不是因為你寫的。 你不得不說:

Interface1 interface1 = new Imple();

您可以創建一個Interface類型的變量,然后將其實例化為實現該接口的類。 您經常使用Java集合看到這一點,例如:

List<String> a = new ArrayList<String>();

實際上,您應該通過定義它們的接口來引用方法,但是您需要一個實際的實現類。 所以我通常會這樣做:

// the variable is of type Interface1
Interface1 interface1 = new Imple();
// but the method will be executed on the Imple object
interface1.method();

不,您需要對實現接口的對象進行調用,而不是在接口本身上進行調用。

編輯:可以使用具有該類型的變量,但它仍然需要是實現該類型的類。 您無法創建接口的實例。

沒有。

由於您無法實現接口,因此您必須創建一個Imple對象,將其用作Interface1如下所示:

Interface1 interface1 = new Imple();

interface1.method();

實際上,接口的主要興趣來自於讓方法返回實現它的任何對象的能力,而不必擔心給定的實現。 在你的情況下,它可以顯示為

public class CheckCall {
    public Interface1 factoryMethod() {
        return new Imple();
    }

    public void test() {
        Interface1 used = factoryMethod();

        used.method();
    }
}

暫無
暫無

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

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