-1

Its possible that class take only the same variable type (int + int || string +string). I use generics type and i don't know that is possible?

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);
     }
});
Anlon Burke
  • 397
  • 4
  • 12
sadasdaaaa
  • 31
  • 8
  • 2
    When you want only one type at a time, then why do you use two different generic types? Just use one ... – Tom May 28 '17 at 07:24
  • yes, but i use string + int it s compile – sadasdaaaa May 28 '17 at 07:25
  • I think you are overthinking this. Just use one generic parameter. – Sweeper May 28 '17 at 07:26
  • this may help: https://stackoverflow.com/questions/6954009/can-i-create-a-generic-method-that-accepts-two-different-types-in-c-sharp – BenKoshy May 28 '17 at 07:56
  • Did you edit the code of your question as an answer to the original question, or are you still having further problems after making that change? – Eran May 28 '17 at 09:13

2 Answers2

0

Of course - just define your class with a single generic type parameter:

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());
Eran
  • 387,369
  • 54
  • 702
  • 768
  • and i use string and integer its working it s must take two the same types – sadasdaaaa May 28 '17 at 07:35
  • @sadasdaaaa It will take any number you wish of parameters of the same type. Using a single type parameter means that all the values you pass to your constructor must match the type you used in the declaration of `p2` (String in this example). – Eran May 28 '17 at 07:39
0

You could use a single type-argument for multiple members:

public class Para2 <K> {
    private K value_1;
    private K value_2; // Also uses K

    // all the methods are changed to fit this change
}

Note, btw, that you can't use a type argument to refer to a primitive type like int in Java. You'll have to use the wrapper class Integer instead.

Mureinik
  • 297,002
  • 52
  • 306
  • 350