在Java中,我們可以將物件引用轉換為介面引用嗎?如果可以,在什麼情況下?


是的,可以。

如果您實現了一個介面,並從一個類中為其方法提供了方法體。您可以使用介面的引用變數來儲存該類的物件,即,將物件引用轉換為介面引用。

但是,使用這種方法只能訪問介面的方法,如果嘗試訪問類的方法,則會生成編譯時錯誤。

示例

在下面的Java示例中,我們有一個名為MyInterface的介面,它包含一個抽象方法display()。

我們有一個名為InterfaceExample的類,它包含一個方法(show())。除此之外,我們還實現了介面的**display()**方法。

在main方法中,我們將類的物件賦值給介面的引用變數,並嘗試呼叫這兩個方法。

interface MyInterface{
   public static int num = 100;
   public void display();
}
public class InterfaceExample implements MyInterface{
   public void display() {
      System.out.println("This is the implementation of the display method");
   }
   public void show() {
      System.out.println("This is the implementation of the show method");
   }
   public static void main(String args[]) {
      MyInterface obj = new InterfaceExample();
      obj.display();
      obj.show();
   }
}

編譯時錯誤

編譯上述程式時,會產生以下編譯時錯誤:

InterfaceExample.java:16: error: cannot find symbol
   obj.show();
      ^
symbol: method show()
location: variable obj of type MyInterface
1 error

要使此程式執行,您需要刪除呼叫類方法的行,例如:

示例

 線上演示

interface MyInterface{
   public static int num = 100;
   public void display();
}
public class InterfaceExample implements MyInterface{
   public void display() {
      System.out.println("This is the implementation of the display method");
   }
   public void show() {
      System.out.println("This is the implementation of the show method");
   }
   public static void main(String args[]) {
      MyInterface obj = new InterfaceExample();
      obj.display();
      //obj.show();
   }
}

現在,程式可以成功編譯和執行。

輸出

This is the implementation of the display method

因此,只有當您只需要呼叫介面的方法時,才需要將物件引用轉換為介面引用。

更新於:2019年7月30日

7K+ 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.