Can I achieve adding integers and concatenating strings in one common method?

I study Generics. I wrote the following code for practice only. In this code, I created one general method for adding two numbers and concatenating two strings according to the values ​​provided by the method call, it should add integer or concatenate strings.

class Kaushal28{

public <T> void  add(T a, T b){

  //System.out.println(a+b);

}    
}
public class NewClass59 {
    public static void main(String args[]){

        Kaushal28 k = new Kaushal28();
        k.add(5, 8);
        k.add("5","8");
}
}

I'm not sure if this can be done in one way or not. If not, what could be the solution to this problem? Can I achieve this using a generic class?

+4
source share
2 answers

You cannot use this as a general method, but you can have a general strategy :

interface Adder<T> { T add(T a, T b); }

String Integer:

class StringAdder implements Adder<String> {
  @Override public String add(String a, String b) {
    return a + b;
  }
}

class IntegerAdder implements Adder<Integer> {
  @Override public Integer add(Integer a, Integer b) {
    return a + b;
  }
}

" " :

<T> void something(Adder<T> adder, T a, T b) {
  System.out.println(adder.add(a, b));
}

something(new StringAdder(), "Hello", "World");
something(new IntegerAdder(), 1, 2);

, :

System.out.println(new StringAdder().add("Hello", "World"));
System.out.println(new IntegerAdder().add(1, 2));
+2

, , , , , Numbers CharSequence:

class Kaushal28 {

    public Number add(Number a, Number b){
        return a.doubleValue() + b.doubleValue();
    }

    public CharSequence add(CharSequence a, CharSequence b){
        StringBuilder sb = new StringBuilder(a.length() + b.length());
        return sb.append(a).append(b).toString();
    }
}
+2

All Articles