该类可能只采用相同的变量类型(int + int || string + string)。我使用泛型类型,我不知道这是可能的吗?
class Para1 <T> {
private T value_1;
private T value_2;
public Para1(T value_1 , T value_2){
this.value_1 = value_1;
this.value_2 = value_2;
}
public void setValue_1(T value_1){
this.value_1 = value_1;
}
public void setValue_2(T value_2){
this.value_2 = value_2;
}
public T get_value_1(){
return value_1;
}
public T getValue_2(){
return value_2;
}
}
a1KlasaButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Para1 p1 = new Para1<>(textArea1.getText(),textArea2.getText());
textField1.setText(p1.get_value_1() + "\n" + p1.getValue_2());
super.mouseClicked(e);
}
});
答案 0 :(得分:0)
当然 - 只需使用一个通用类型参数定义您的类:
public class Para2 <V> {
private V value_1;
private V value_2;
public Para2(V value_1 , V value_2){
this.value_1 = value_1;
this.value_2 = value_2;
}
...
}
...
Para2<String> p2 = new Para2<>(textArea1.getText(),textArea2.getText());
答案 1 :(得分:0)
您可以为多个成员使用单个类型参数:
public class Para2 <K> {
private K value_1;
private K value_2; // Also uses K
// all the methods are changed to fit this change
}
注意,顺便说一下,你不能使用类型参数来引用Java中的int
这样的基本类型。您将不得不使用包装类Integer
。