2012-03-04 28 views
-5

下面的類Fruit沒有實現它使用類接口的方法剝離,它也不是一個抽象類隱藏方法?接口:類沒有implementsaion關鍵字

interface Peelable { 
    int peel(); 
} 

class Fruit { 
    // Return int number of pieces of peel that 
    // resulted from the peeling activity. 
    public int peel() { 
     System.out.println("Peeling is appealing."); 
     return 1; 
    } 
} 

class Apple implements Peelable { 
    private Fruit fruit = new Fruit(); 
    public int peel() { 
     return fruit.peel(); 
    } 
} 

class FoodProcessor { 
    static void peelAnItem(Peelable item) { 
     item.peel(); 
    } 
} 

class Example5 { 
    public static void main(String[] args) { 
     Apple apple = new Apple(); 
     FoodProcessor.peelAnItem(apple); 
    } 
} 
+1

另外,我不明白這個問題。 「水果」是一個不「擴展」或「實現」任何東西的具體類。所以有什麼問題? – 2012-03-04 16:32:11

+2

「水果使用類接口的方法剝離」 - 不,它實現了恰好具有相同名稱的無關方法! 'Fruit'不會在你的代碼中實現'Peelable'。 – DNA 2012-03-04 16:34:57

+0

另外,爲什麼'Apple'有一個'Fruit'作爲一個字段?真的沒有意義... – DNA 2012-03-04 17:03:06

回答

1

Fruit沒有關係(*)來PeelableApple,由於[Fruit]不實現Peelable

他們只是兩類[AppleFruit]或class和interface [FruitPeelable這正好有相同名稱的方法。

(*)不是 - 一個關係更準確。很顯然,Apple有一個Fruit作爲一個字段。