私は実行している問題があり、それを記述するための技術用語はわからないので、検索するのは難しい自分自身の答えと私は誰かがここで何が起こっているいくつかの光を流すことができるかもしれないことを望んでいる。Javaライブラリ内の2つ以上の類似した子クラス内に重複したメソッド定義を避ける
ライブラリに、JTextFieldやJTextAreaなど多少類似した機能を持つ2つ以上の同様のクラスがあるとします。私は、これらのクラスの両方で追加のメソッドを利用できるようにしたいと考えています。
私は両方のクラスを拡張してそれぞれにメソッドを追加することができますが、追加するメソッドは非常に似ているので、各クラスにコピーして貼り付けることができます。これにより、これを行うより良い方法があると私には思われます。
この簡略化した例では、することが可能である: A) BながらCustomJTextFieldとCustomJTextArea 間の「getStringValue()」の近くの重複定義を排除する)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);
}
}
}
私の不満は、私はただのJTextFieldとJTextAreaにの機能を失うことなくJTextComponentのを延長するように見えることができないこととなっているが、両方が拡張されている場合、それは不必要な重複のように感じています。このような重複を避けるためのエレガントな方法はありますか?
ありがとうございます! – Zachary
あなたは大歓迎です。 :-) – PNS