ovod ovod - 5 months ago 7
Java Question

java - I don't undestand method syntax

I have the class:

public abstract class Entry{
protected static <T extends Entry> List<T> all(Class<T> cls) {
blah blah
}


And the child of it:

class Article extends Entry {
public static List<Article> all() throws SQLException {
return Entry.all(Article.class);
}
}


I don't understand the syntax of the method:

protected static <T extends Entry> List<T> all(Class<T> cls)


Why can we not just do it like this?:

protected static List<T> all(Class<T> cls)

Answer
protected static <T extends Entry> List<T> all(Class<T> cls)

This means that the method named all has a type parameter T which must be a subtype of Entry (or Entry itself).

Generic Methods in Oracle's Java Tutorials explains the syntax and what this means.

Why we just can not do like this?:

protected static List<T> all(Class<T> cls)

Because the compiler doesn't automatically know that with T you mean a type parameter instead of a concrete type.

Note that for type parameters, a single upper-case letter is most often used for the name of the type parameter. But this is only a convention. You could use any name that is a valid identifier.

If a name is supposed to be a type parameter, it has to be declared as such, otherwise the Java compiler assumes it's a concrete type.

Comments