Java 在泛型类重写中,为什么某些类返回空值?请执行以下代码

Java 在泛型类重写中,为什么某些类返回空值?请执行以下代码,java,Java,通用覆盖的程序: 类代码:包含genric super和泛型子类,它们具有show as Overrided ans,试图根据重写的方法将执行的条件来确定 class GA<T>{ private T type; public GA(){ } public GA(T type) { this.type = type; } public <T> void show(){ System.out

通用覆盖的程序: 类代码:包含genric super和泛型子类,它们具有show as Overrided ans,试图根据重写的方法将执行的条件来确定

class GA<T>{
    private T type;
    public GA(){

    }
    public GA(T type) {
         this.type = type;
    }
    public <T> void show(){
        System.out.println("GA:"+this.type);
    }
}
class GB<T> extends GA<T>{
    private T type;
    public GB(T type) {
        this.type = type;
    }

    public <T> void show(T type){
        System.out.println("GB:"+type);
    }
}

public class VarArg {
    public static <T> void show(T... a) {
        System.out.println("Element Length:" + a.length);
        for (T aa : a) {
             System.out.println("Element:" + aa);
        }
    }

    public static void main(String[] args) {
        show(5, 5, 5, 5);
        show(5.2, 5.1, 5.5);
        GA[] arrayStr = {new GA<String>("Str"),new GB<Integer>(10),new GA<Double>(5.5)};
        for(GA ga: arrayStr ){
            ga.show();
        }
        GA<String> str = new GB<String>("H");
        str.show();
    }
}
你的私人T型;类中的GB实际上是与GA中的type不同的字段,因为在子类中不可能重写或重新声明超类的字段。现在,在GB的构造函数中,由于没有显式的super…,因此隐式地调用了超类的默认构造函数-这使得GA.this.type为null


此外,类GB中的show方法不会被重写,因为它的参数列表与GA中的不同。除此之外,它在任何地方都不会被调用。

您没有在GB的构造函数中调用supertype,GA的默认构造函数使类型保持未初始化状态。有两个类型字段相互隐藏。您希望这样吗?您可以通过从VarArg类中删除show方法来简化示例。这种方法与你的问题无关。
Element Length:4
Element:5
Element:5
Element:5
Element:5
Element Length:3
Element:5.2
Element:5.1
Element:5.5
GA:Str
GA:null
GA:5.5
GA:null