Skip to content

Commit 444e45f

Browse files
committed
feat(generic-methods): add example of generic method with type parameter <T>
WHAT: - Implemented `Test4` class showcasing a static generic method `genericDisplay(T element)`. - Method prints both the runtime class type and the value of the passed argument. - Demonstrated usage with `Integer`, `String`, and `Double` inputs. WHY: - Highlights how **generic methods** differ from generic classes/interfaces. - Shows type inference in action — no explicit type declaration is needed at the call site. - Reinforces the concept of compile-time type safety with generics while maintaining runtime flexibility. HOW (Logic Flow): 1. Define a generic method `static <T> void genericDisplay(T element)`. 2. Use `element.getClass().getName()` to print the runtime type of the object. 3. Invoke method with different types (`Integer`, `String`, `Double`) without casting. BENEFITS: - Avoids method overloading for different data types. - Promotes **code reusability** and **type safety** in utility methods. - Enables compile-time checks while working seamlessly across multiple types. REAL-WORLD APPLICATIONS: - Utility libraries (e.g., logging frameworks, data serializers) where methods need to handle arbitrary object types. - Collection processing (printing, transformation, or validation of heterogeneous data). - Framework design (e.g., Spring, Hibernate) where methods often use generics for maximum flexibility. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 8b93867 commit 444e45f

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,12 @@
1-
/*
2-
We can also write generic functions that can be called with different types of arguments based on the type of arguments passed to the generic method. The compiler handles each method.
3-
*/
1+
package GenericMethods;
42

5-
class Test4
6-
{
3+
class Test4 {
74
// A Generic method example
8-
static <T> void genericDisplay(T element)
9-
{
5+
static <T> void genericDisplay(T element) {
106
System.out.println(element.getClass().getName() + " = " + element);
117
}
128

13-
public static void main(String[] args)
14-
{
9+
public static void main(String[] args) {
1510
// Calling generic method with Integer argument
1611
genericDisplay(11);
1712

@@ -20,4 +15,10 @@ public static void main(String[] args)
2015
// Calling generic method with double argument
2116
genericDisplay(1.0);
2217
}
23-
}
18+
}
19+
20+
/*
21+
We can also write generic functions that can be called with different types of arguments based on the type of arguments
22+
passed to the generic method.
23+
The compiler handles each method.
24+
*/

0 commit comments

Comments
 (0)