2013-12-16 119 views
0

我有這個練習我想要做,但是我對它有點掙扎。 它說:實現接口的對象的方法?

「寫一個靜態方法打印這需要對象,它們的 類實現可打印,並且打印所述陣列中的每個元素,每行一個 元件的陣列通過將其放置在另外的檢查它。空類 和編譯它。「

如何編寫需要爲實現接口的參數對象的方法,我想我需要使用‘實現打印’,但在哪裏?無法弄清楚..我知道如何在課堂上做到這一點,但...方法?

+0

實現Printable的類是聲明爲實現Printable的類。方法參數將是該類型的數組。 –

+1

'void method(Printable [] objects){...}' – Flavio

+0

謝謝@Flavio :) –

回答

2

你的靜態方法需要接受一個Printable數組作爲參數,例如:

public static void print(Printable[] printables) 
2

只需使用接口作爲數組的類型。就像這樣:

public static void print(Printable[] objectArray) { 
    //All objects in objectArray implement the interface Printable 
} 
1

的練習要求執行三項任務:

  1. 定義一個名爲Printable*
  2. 編寫需要Printable[]作爲參數
  3. 寫一個靜態方法的接口一個空的類實現Printable
  4. 在你的main方法,創建一個Printable的數組,然後用步驟3中定義的類的實例填充
  5. 將步驟4中定義的數組傳遞給步驟2中定義的靜態方法,以檢查代碼是否正常工作。

下面是一個接口的建議:

public interface Printable { 
    void print(); 
} 

下面是類實現Printable一個建議:

public class TestPrintable implements Printable { 
    public void print() { 
     System.out.println("Hello"); 
    } 
} 

靜態方法應該看起來像這樣的簽名:

public static void printAll(Printable[] data) { 
    ... // Write your implementation here 
} 

該測試可以是這樣的:

public void main(String[] args) { 
    Printable[] data = new Printable[] { 
     new TestPrintable() 
    , new TestPrintable() 
    , new TestPrintable() 
    }; 
    printAll(data); 
} 


* Java defines an interface called Printable,但目的不同。