Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question regarding overloaded methods vs generics

 
Dinuka Arsakularatne
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i just finished reading the generics and colletion chapter of the SCJP study guide. after reading that i figured that without using overloaded methods you can use generics to make one method accept many different types. am i correct? and the other thing is if you declare a method such as

public <T extends Number> Integer test(T in){

return in;
}
and if i pass a Float or a Double will it convert it to a Integer and return the value?


thank you.
 
Stephen O'Kane
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
not being a complete expert, I can only suggest you take my opinion with a pinch of salt.

I believe that when you pass in a Float or Double it won't cause a problem, but when you try to return that value you passed in, it will cause a comiler failure, as Float or Double ain't an Integer.

if you pass in a Float, you should imagine the method like this



you cannot return a Float when an Integer is expected

Sok
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic