skip
skip

Reputation: 12653

Why type parameter required before return type for static generic methods

The following noGood method gives a compilation error because it omits the formal type parameter immediately before the return type T.

public static T noGood(T t) {
  return t;
}

Could somebody please help me understand that why is it required for a static generic method to have a type parameter before the return type? Is it not required for a non-static method?

Upvotes: 8

Views: 1343

Answers (4)

John Humphreys
John Humphreys

Reputation: 39294

First of all, this is pretty standard in languages. Even in C++:

template <class myType>
myType GetMax (myType a, myType b) {
    return (a>b?a:b);
}

You declare the type parameter above a generic function.

When its a member function of a class, it has access to the class's type parameters. When its static it doesn't, so you need to declare them explicitly.

Upvotes: 1

azro
azro

Reputation: 54148

When you're using generic, you need to declare them, using <> notation

  1. In a class

    public class Foo<T, U, V>{
    
    }
    
  2. In a method, before the return type

    public static <T, U extends Number, V> T foo(T t) {
        U u = ..;
        ...
    }
    
    public static <T> int foo(T t) {
        ...
    }
    

Upvotes: 2

Mureinik
Mureinik

Reputation: 311508

The type parameter (T) is declared when you instantiate the class. Thus, instance methods don't need a type argument, since it's defined by the instance.

static methods, on the other hand, don't belong to an instance - they belong to the class. Since there's no instance to get the type information from, it must be specified for the method itself.

Upvotes: 9

Andrew
Andrew

Reputation: 49626

T wasn't defined. The order of modifiers and the return type remains the same.

public static <T> T noGood(T t) {
    return t;
}

Upvotes: 2

Related Questions