2012-12-19 63 views
6

我已經實現接口B.接口沒有setter方法

B ref = new A(); 

代碼的具體類答:

public interface B{ 
    public abstract String[] getWords(); 
} 

public class A implements B { 
    private String[] words = new String[] {}; 
    public void setWords(String[] words){ 
    this.words = words; 
    } 
    public String[] getWords(){ 
    return this.words; 
    } 
} 

在接口B,我只有getter方法,但不雖然A類有這個方法

所以,當我這樣做:B ref = new A();,這個代碼將工作,我將如何設置單詞?

回答

4

你要轉換回原來的類型,如果接口不公開它

if (ref instanceof A) 
    ((A) ref).setWords(words); 
else 
    // something else. 

一個更好的解決方案是將方法添加到該接口。

5

如果定義爲B ref = ...,您將無法致電setWords

這是在需要使用聲明變量時的確切類型(或使用流延)的情況之一:

A ref = new A(); 

或者:

  • 可以創建一個C接口它擴展了B幷包含兩種方法並且具有A實現C.
  • 您可以在A中提供一個構造函數,它需要一個String[] words參數來初始化words字段,並且不會在al中提供setter湖

我個人傾向於後一種選擇:

public class A implements B { 

    private final String[] words; 

    public A(String[] words) { 
     this.words = words; 
    } 

    public String[] getWords() { 
     return this.words; 
    } 
} 
+0

感謝所有的答覆。 – Mercenary

5

所以,當我這樣做:乙REF =新的A();,將這段代碼工作...

是的,它會的。

...以及如何設置字詞?

你將不能夠除非你:

  1. 化妝A的構造帶的單詞列表;或
  2. add setWords() to B;或
  3. 保留對您的對象類型A的參考;或
  4. downcast ref to A

其中,我會選擇1-3中的一個。最後一個選項僅用於完整性。

3
B ref = new A();//1 
ref.setWords(whatever);//2 

上面的代碼將無法編譯爲setWords()是不是在你的interface B定義,你會得到第2行

其他在他們的答案已經表達了一個編譯器錯誤。你有兩個選擇作爲變通

  • 創建對象爲A ref = A();
  • 向下推倒A類型,如((A)ref).setWords(watever);
0

所以,當我這樣做:乙REF =新的A();,將這個代碼工作

,我將如何設置的話嗎?

你不行。您需要在界面中使用setter方法。

您不需要將方法定義爲摘要。這是默認的抽象。