Java Generics: special use of <T extends Object & Interface>

I often find code that uses generics in Java as follows:

public static <T extends Object & Interface> foo(T object) {
    ...
}

Since in Java every class is inherited from the class of the object, I'm not sure if extends Objectit gives special meaning or is used for special purposes. Can someone tell me if there is another background using this or is it implied if you take <T extends Interface>?

+4
source share
3 answers
<T extends Object & Interface>

What is Objectclearly redundant and usually equal

<T extends Interface>

Please note that using Interfaceas a class name is very discouraged.

+5
source

, T Object. T extends Object , (, , ) , T extends Interface.

0

, . , :

public class Utils {
    public static <T> int length(T obj) {
        if(obj instanceof CharSequence) {
            return ((CharSequence)obj).length();
        }
        return 0;
    }
}

, :

public class Main {
    public static void main(String... args) {
        System.out.println(Utils.length("foo"));
    }
}

. , - CharSequence, 0 , , CharSequence. ,

public static <T extends CharSequence> int length(T obj) { ... }

, Main , java.lang.NoSuchMethodError. , . int length(Object obj), int length(CharSequence obj). Main, , . , :

public static <T extends Object & CharSequence> int length(T obj) { ... }

CharSequence, int length(Object obj) ( A & B & C & ..., ), Utils .

0

Source: https://habr.com/ru/post/1609081/


All Articles