簡體   English   中英

將類轉換為不相關的接口

[英]Casting a class to an unrelated interface

顯然,這會導致編譯錯誤,因為 Chair 與 Cat 無關:

class Chair {}
class Cat {}

class Test {
   public static void main(String[] args) {
       Chair chair = new Char(); Cat cat = new Cat();
       chair = (Chair)cat; //compile error
   }
}

為什么當我將 Cat 引用投射到不相關的接口 Furniture 時,我只會在運行時收到異常,而編譯器顯然可以告訴 Cat 沒有實現 Furniture?

interface Furniture {}

class Test {
   public static void main(String[] args) {
       Furniture f; Cat cat = new Cat();
       f = (Furniture)cat; //runtime error
   }
}

編譯的原因

interface Furniture {}

class Test {
   public static void main(String[] args) {
       Furniture f; Cat cat = new Cat();
       f = (Furniture)cat; //runtime error
   }
}

是你很可能有

public class CatFurniture extends Cat implements Furniture {}

如果您創建CatFurniture實例,則可以將其分配給Cat cat並且該實例可以轉換為Furniture 換句話說,某些Cat子類型可能確實實現了Furniture接口。

在你的第一個例子中

class Test {
    public static void main(String[] args) {
        Chair chair = new Char(); Cat cat = new Cat();
        chair = (Chair)cat; //compile error
    }
}

這是不可能的,有些Cat亞型延伸Chair ,除非Cat本身延伸Chair

暫無
暫無

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

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