2016-07-28 75 views
0

我遇到了一個問題,我不知道描述它的技術術語,因此我很難搜索一個答案我自己,我希望有人能夠闡明這裏發生的一切。在Java庫中的2+類似子類中避免重複的方法定義

假設一個庫有兩個或更多類似功能的類,比如JTextField和JTextArea。我想爲這兩個類提供一個額外的方法。

我可以擴展這兩個類併爲每個類添加方法,但要添加的方法可能非常相似,以至於它可以複製並粘貼到每個類中。這讓我覺得有一個更好的方法來做到這一點。

在這個簡化的例子中,是有可能: A)消除「向GetStringValue()」 CustomJTextField和CustomJTextArea之間 而 B)保持兩者的JTextArea和JTextField的原始功能的近重複定義。

概念性的一例:

public interface AnInterface { 
    public String getStringValue(); 
} 

public class CustomJTextField implements AnInterface{ 
    //Could Duplication of this method be avoided? 
    @Override 
    public String getStringValue(){ 
     return this.getText(); 
    } 
} 

public class CustomJTextArea implements AnInterface{ 
    //Mirrors CustomJTextField's definition 
    @Override 
    public String getStringValue(){ 
     return this.getText(); 
    } 
} 

public class CustomJCheckbox implements AnInterface{ 
    @Override 
    public String getStringValue(){ 
     return this.isSelected() ? "Checked" : "Not Checked"; 
    } 
} 

public class Main{ 
    public static void main(String[] args) { 
     ArrayList<AnInterface> items = new ArrayList<AnInterface>(); 
     items.add(new CustomJTextField()); 
     items.add(new CustomJTextArea()); 
     items.add(new CustomJCheckbox()); 

     for (AnInterface item : items){ 
      String output = item.getStringValue(); 
      System.out.println(output); 
     } 
    } 
} 

我無奈一直是我似乎不能僅僅延長的JTextComponent不失的JTextField和JTextArea中的功能,但如果兩者都伸展,感覺就像不必要的重複。有沒有一種優雅的方式來避免這種重複?

回答

1

如果您使用Java 8,那麼default方法實現在interface的定義中,提供了一個很好的解決方案。

在上述示例中,可以定義爲AnInterface

public interface AnInterface { 
    public getText(); // Abstract method (re)definition 

    default String getStringValue() { 
     return this.getText(); 
    } 
} 

並且僅覆蓋爲CustomJCheckboxgetStringValue()方法。

當然,以上對於具有微不足道(例如,1行)實施方法的價值很小。然而,這對於複雜的方法非常有用。

+0

謝謝親切! – Zachary

+0

非常歡迎。 :-) – PNS

相關問題