Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics methods: static vs NON-static

Directly from this java tutorial:

For static generic methods, the type parameter section must appear before the method's return type.

Is it not true for NON-static generic method? If not what's the NON-static generic method syntax? Thanks in advance.

like image 341
Rollerball Avatar asked Jun 26 '13 13:06

Rollerball


3 Answers

The syntax for declaring non-static generic methods is the same as for static methods, just without the static keyword: generic type parameters are placed before the return type.

class Example {
     public <E> void method(E param) { }
}

Non-static methods may also use the generic type parameter of the enclosing class, like below. These are not considered generic methods; a generic method is one that declares type parameters.

class Example<T> {
     // Not a generic method!
     public void method(T param) { }
}
like image 186
Joni Avatar answered Nov 09 '22 12:11

Joni


This is true for any generic methods.

public <T> T f() {
    return this.<T> f();
}
like image 7
kennytm Avatar answered Nov 09 '22 11:11

kennytm


That statement is true for all generic methods, because that is the very definition of a generic method -- a generic method is one that declares type parameters.

like image 2
newacct Avatar answered Nov 09 '22 13:11

newacct