• Post Reply Bookmark Topic Watch Topic
  • New Topic

How can void method have return type in generics  RSS feed

 
Ranch Hand
Posts: 189
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For a method in generics with void return type the declaration mentions the type. How can a void method have a return type? Also, what if a method with void return type accept input parameters which are of different types? How to declare such a method? Also for a method which has a return type, the return type is mentioned 2 times as shown in the second example below. Why?

Declaration Example of method which does not return anything in generics:



Declaration Example of method which has a return type in generics:









 
Greenhorn
Posts: 7
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you simply write:



then the compiler would interpret T as a class or interface instead of a generic, resulting in an error message such as:
T cannot be resolved to a type
The token <T> is needed to tell the compiler that this method is generic. It is not a return type.
If you want a method that accepts two different generic arguments you can do it this way:



and use it this way:

 
Ranch Hand
Posts: 128
4
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What does Generic method mean?
 
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yosuf Ibrahim wrote:What does Generic method mean?


A generic method is a feature of the Java Language. It is the ability to define a method with type parameters -- parameters whose type is determined when it is used (still compile time, of course).

https://docs.oracle.com/javase/tutorial/java/generics/methods.html

Henry
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!