我遇到了一个问题,我不知道描述它的技术术语,因此我很难搜索一个答案我自己,我希望有人能够阐明这里发生的一切。在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中的功能,但如果两者都伸展,感觉就像不必要的重复。有没有一种优雅的方式来避免这种重复?
谢谢亲切! – Zachary
非常欢迎。 :-) – PNS