繁体   English   中英

在Java中使用泛型进行继承

[英]Inheritance using Generics in Java

class A<E>{

}
class B<E> extends A{

}

public class WildInDeclare<E>{
    public static void main(String[] args){
        A<Integer> obj = new B<Integer>();
    }
}

当我编译以上程序时,出现此错误。

Note: WildInDeclare.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

之后,我只将class B<E> extends A{替换为class B<E> extends A<E>{ 它工作正常,您能解释一下为什么在代码继承过程中需要再次编写A<E>吗?

我面临的第二个继承问题。 我用以下代码更新上面的代码。

class A<E>{
    public A(E o){

    }
}
class B<E> extends A{
    public B(){
        super(E);
    }
}

public class WildInDeclare<E>{
    public static void main(String[] args){
        A<Integer> obj = new B<Integer>();
    }
}

但是为什么不编译呢? 我收到以下错误。

WildInDeclare.java:8: error: cannot find symbol
                super(E);
                      ^
  symbol:   variable E
  location: class B<E>
  where E is a type-variable:
    E extends Object declared in class B
Note: WildInDeclare.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error

如何将Parameter传递给Parent类?

您能解释一下为什么需要再次写A吗

因为A是采用一个类型参数的泛型类。 理想情况下,您将不能引用原始类型A ,而只能引用A<String>A<Integer>A<Map<K, List<O>>等。Java让您使用原始类型是为了向后兼容,但原则上必须提供该参数。

当您说类B扩展了A ,您仍然需要说它扩展了什么类型的A 即通用参数是什么。 (这并不需要是相同的B的泛型参数-例如,你可以定义B<E> extends A<String> ,这将是一致的。)

以下代码...未编译。 为什么?

该代码在语法上是无效的。 您已定义A的构造函数以采用其通用参数类型的对象 因此,当您从B的构造函数调用super() ,您需要传递此类对象。 E不是对象-它只是B泛型参数的名称。 因此,编译器正确地说“找不到符号”,在范围内没有所谓的E

如果您希望B接受一个只是传递给超类构造函数的输入参数,它将看起来像这样:

class B<E> extends A<E> {
    public B(E e) { // this parameter could be called anything, doesn't have to be e
        super(e);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM