The methods which can handle different types of arguments are known as generic methods. Types of the argument are specified on method call.
Syntax: generic method can includes comma separated multiple type parameter, inside angle brackets and appears before the method’s return type.
public static <T, U> T identical(T obj1, U obj2){ return returnValue; } |
Example:
GenericsTest.java
/** * This class is used to show the use of * generics method with two parameters. * @author javawithease */ class Test { //Generics method with two parameters. public <T, U> void showItemDetails(T itemT, U itemU){ System.out.println("Value of the itemT: " + itemT); System.out.println("Type of the itemT: " + itemT.getClass().getName()); System.out.println("Value of the itemU: " + itemU); System.out.println("Type of the itemU: " + itemU.getClass().getName()); } } public class GenericsTest { public static void main(String args[]){ //String type test Test test = new Test(); test.showItemDetails("Test String.", 100); } } |
Output:
Value of the itemT: Test String. Type of the itemT: java.lang.String Value of the itemU: 100 Type of the itemU: java.lang.Integer |
No comments:
Post a Comment