Java 带参数的泛型 - 继承

Java generics with parameter - inheritance

我有以下代码:

public class Inheritance {

    class A<T,U,V>{

    }

    class B<T,U,V> extends A<T,U,T>{        

    }
}

有人可以向我解释一下它是如何工作的吗? Class B 是否只扩展了 A class,参数是 "T,U,T",还是扩展了实际的 A"T,U,V" class?

AT=BT
AU = BU
AV=BT

B<String, Integer, Void> b = null;
A<String, Integer, String> a = b;

Does the Class B extend only A class, which parameters are "T,U,T"

是的,完全正确。

or it extends the actual A"T,U,V" class?

这是一个模板,没有实际的通用参数。这是一种将您自己的参数类型与父级参数类型相匹配的方法。如果有一个 B<String, Integer, Long> 实例,就会有一个父对象 A<String, Integer, String> 支持它。

举个例子:

 public class Inheritance {
        public static class A<T,U,V>{
             T t;
             U u;
             V v;

             A(T t, U u, V v) {
                this.t = t;
                this.u = u;
                this.v = v;
            }

            T getT() {return t;}
            U getU() {return u;}
            V getV() {return v;}
        }

        public static class B<T,U,V> extends A<T,U,T>{
            public B(T t, U u, V v) {
                super(t, u ,t);
            }
        }

        public static void main(String[] args) {
            B<Boolean, Integer, String> b = new B<>(false, 1, "string");
           // 't' attribute is Boolean 
           // since type parameter T of class B is Boolean
           Boolean t = b.getT(); 
           // 'v' attribute is Boolean 
           // since type parameters T and V of class A must have the same type as 
           // type parameter T of class B 
           Boolean v = b.getV(); 
        }
    }

基本上 class B 扩展了 class A(具有三个通用参数)。通过声明 B<T,U,V> extends A<T,U,T> 您只需将 A 的第一个和 A 的第三个通用参数绑定到相同类型的 B 的第一个参数

如 class B 的构造函数中的示例所示,我们具有三种不同的类型 - 布尔值、整数、字符串,但在 class A 的构造函数中,我们只有两种不同的类型布尔值和整数,因为class A 的第一个和第三个构造函数参数都绑定到布尔类型

可以在此处找到有关泛型和继承的更多信息: https://docs.oracle.com/javase/tutorial/java/generics/inheritance.html

在这段代码中,每个 class 的模板化类型“identifiers”没有相互链接,让我修改一下代码片段来解释我的意思:

public class Inheritance {
    class A<T,U,V> { }

    class B<I,J,K> extends A<I,J,I>{ }
}

代码和之前一样。可以看到I,J,K和T,U,V之间没有"naming"相关性。

此处将类型 I 和 J 转发给 A。从 A 的角度来看,替换为:T=I,U=J,V=I。