2016-07-28 73 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

相关问题