• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

why static generic method should have<T> in front of return type

 
Ranch Hand
Posts: 594
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Why a generic static method have a in addition to return type, but a instance method not? public class Main {

public  static <T> T met(T t) {
   return t;
}

public  T met1(T t) {
   return t;
}
}
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
<T> represent the type of object. Here it is any Object can be returned. Generics can be returned for non static methods too
 
Sheriff
Posts: 22862
132
Eclipse IDE Spring TypeScript Quarkus Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch, Ramesh Suri!

Jacob, the reason is quite simple - how else would you specify the generic type? Non-static methods can "inherit" the generic type from their instance, but static methods don't have an instance. But Ramesh Suri is right, non-static methods can also have a generic type of their own, also combined with the instance's generic type (as long as they have different names).
 
Bartender
Posts: 15743
368
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
One such example is Stream.map(). The Stream class declares a generic type parameter T, but the map() instance method declares a second type parameter called R.
 
reply
    Bookmark Topic Watch Topic
  • New Topic