java - What are the benefits of using Generics? -
this question has answer here:
- what point of t extends someclass? 1 answer
i new generics in java. have few doubts benefits of using generics. please refer below code -
<t extends bounceable> void gogreen(t ob); void gogreen(bounceable ob);
here bounceable interface.
can please explain me difference in above definitions. both restrict caller passing object not bounceable type. if possible implement same code in interface style, benefit of using generics? in advance.
if returning nothing in example, haven't gained using generics. other declaration useful.
on other hand, generics allow create following method:
<t extends bounceable> t gogreen(t ob);
this returns object of same type pass in, in lot of scenarios save cast.
quote @luiggimendoza's excellent example comments:
assume have ball implements bounceable
, cellphone implements bounceable
. when pass ball
method, expect method return ball
, not cellphone
.
this not possible achieve non-generic approach.
Comments
Post a Comment