Lab Objective: In this lab, we will demonstrate a generic method and class. By the end of this lab, learners will be able to utilize the generic method and class.
Java Generics Method
We can create a method that can be used with any type of data. That method is known as the Generics Method.
Create a class named DemoClass. As shown below, we will create a generic method in this class:
Public classDemoClass {// create a generics methodpublic <T> voidgenericsMethod(T data) {System.out.println("Generics Method:");System.out.println("Data Passed: "+ data); }}
Create a class named myRunner. In this class, we will invoke the generic method.
publicclassmyRunner {publicstaticvoidmain(String[] args) {// initialize the class with Integer dataDemoClass dObj =newDemoClass();dObj.genericsMethod(25); // passing intdObj.genericsMethod("Per Scholas"); // passing StringdObj.genericsMethod(2563.5); // passing floatdObj.genericsMethod('H'); // passing Char }}
Output:
Generics Method:
Data Passed: 25
Generics Method:
Data Passed: Per Scholas
Generics Method:
Data Passed: 2563.5
Generics Method:
Data Passed: H
In the above example, we have created a generic method named genericsMethod.
public <T> void genericMethod(T data) {...}
Here, the type parameter <T> is inserted after the public modifier and before the return type void.
We can call the generics method by placing the actual type <String> and <Integer> inside the bracket before the method name.
Generic Class
A class can have more than one type parameter. In this case, the type parameters are separated by a comma.
For the demonstration, we will initialize two type parameters in the Generic class. The names of the parameter types will be Datatypeone and DatatypeTwo, but these are only names. You are free to use “X” or “Z,” or any other identifier to name parameters.
Create a class named GMultipleDatatype: Write the below code.