By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,804 Members | 1,364 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,804 IT Pros & Developers. It's quick & easy.

How to add the two integers in this generic program.

P: 1
Expand|Select|Wrap|Line Numbers
  1. /**
  2. * @(#)demoGen.java
  3. *
  4. * @version 1.00 2013/9/6
  5. */
  6.  
  7. public class demoGen {
  8.  
  9. public demoGen(T t1,T t2) {
  10. System.out.println(t1+t2);
  11. }
  12.  
  13. public static void main(String[] args) {
  14.  
  15. demoGen dem=new demoGen(10,15);
  16. demoGen demo=new demoGen("You are ","good");
  17.  
  18. }
  19. }
Aug 6 '13 #1
Share this Question
Share on Google+
1 Reply


Expert 100+
P: 785
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.intValue() + (Integer)t2.intValue()". (Maybe ".intValue()" is not needed with auto-in/outboxing, but I can't verify that at the moment)
Aug 7 '13 #2

Post your reply

Sign in to post your reply or Sign up for a free account.