Defining generic methods

Generics is not limited to defining generic classes.

We can define generic methods in our normal classes as well.

Lets see how can we use generic methods.

public static <T extends Number & Comparable> void myGenericMethod(T obj) {
    System.out.println(obj.getClass().getName());}

As you can see in the above code snippet, we just need to define the parameter type before the method return type.

Generic methods also support the bounded types as supported by the generic classes.

The example for the generic method can be found here

It is even possible for constructors to be generic.

Since we are talking about generic methods, lets talk a bit about method overloading.

Consider the below example. We have two methods as below :

void myGenericMethod(ArrayList<String> lst) {};
void myGenericMethod(ArrayList<Integer> lst) {};

Lets first take a look at how compilation happens for generic code.
1. Code compiled with generic syntax
2. Generic syntax removed.
3. Code re-compiled without generic syntax.

So in the above scenario, the methods left after point 2 are :
void myGenericMethod(ArrayList lst) {};
void myGenericMethod(ArrayList lst) {};

which means that both are having the same syntax.

This will result into a compilation error saying that both methods have same erasure. i.e. after removal of generic syntax, the method signatures are the same.


Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Collection Framework - Cursors in Java

Hashed data structures