How to add the two integers in this generic program.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • samdaniel
    New Member
    • Aug 2013
    • 1

    How to add the two integers in this generic program.

    Code:
    /**
    * @(#)demoGen.java
    *
    * @version 1.00 2013/9/6
    */
    
    public class demoGen {
    
    public demoGen(T t1,T t2) {
    System.out.println(t1+t2);
    }
    
    public static void main(String[] args) {
    
    demoGen dem=new demoGen(10,15);
    demoGen demo=new demoGen("You are ","good");
    
    }
    }
    Last edited by Rabbit; Aug 6 '13, 06:43 PM. Reason: Please use code tags when posting code.
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    Plus "+" is an overloaded operator. It concatenates strings, or adds numbers. The type of input is generic, so it is unclear how to compile it. Have you tried to compile your code? I bet it does not work. So you need to write one method for String and another for numbers. Using numbers, you can use "T extends Number" and instead of "t1 + t2", you can use "t1.doubleValue () + t2.doubleValue( )".
    If you want to have only a single method to handle all, you can define an interface with an "add(t1,t2) " method and implement it in a derived class (derived from String, Integer, Double etc.). Or an easier possibility, but not good code practice: instead of using generic types, define method arguments as "Object" and then add a line "if (t1 instanceof String && t2 instanceof String){result = (String)t1 + (String)t2" for each possible type. For example for adding integers: "if (t1 instanceof Integer && t2 instanceof Integer){result = (Integer)t1.int Value() + (Integer)t2.int Value()". (Maybe ".intValue( )" is not needed with auto-in/outboxing, but I can't verify that at the moment)

    Comment

    Working...