继承泛型类型并强制<type> </type>

时间:2013-01-10 13:57:54

标签: java class generic-type-argument

是否可以继承泛型类型并在子类中强制接收类型?

类似的东西:

class A<GenericType>{}
class B extends A<GenericType>{}

或者:

class B <PreciseType> extends A <GenericType>{}

但是我在哪里定义B中使用的GenericType?

3 个答案:

答案 0 :(得分:2)

鉴于

class A<T> {}

这取决于你尝试做什么,但两种选择都是可能的:

class B extends A<SomeType> {};
B bar = new B();
A<SomeType> foo = bar; //this is ok

class B<T> extends A<T>{}; //you could use a name different than T here if you want
B<SomeType> bar = new B<SomeType>();
A<SomeType> foo = bar; //this is ok too

但请记住,在第一种情况下, SomeType 是一个实际的类(如String),在第二种情况下, T 是泛型类型参数当您声明/创建类型B的对象时需要实例化。

作为一条建议:在集合中使用泛型是简单明了的,但如果你想创建自己的泛型类,你真的需要正确理解它们。关于它们的方差属性有一些重要的问题,所以仔细阅读tutorial并多次掌握它们。

答案 1 :(得分:1)

假设A被声明为class A<T> {}并且您希望仅以String为专业,您可以将其声明为class B extends A<String>

示例:

public class A<T> {
    public T get() {
        return someT;
    }
}

public class B extends A<String> {
    public String get() {
        return "abcd";
    }
}

答案 2 :(得分:0)

class B extends A<GenericType>{}

这是可能的。您的B类将是一个新类,它将特定类作为参数扩展为通用A类,而B将不是泛型类。

class B <PreciseType> extends A <GenericType>{}

在这种情况下,您将创建一个通用类B,它具有通用参数PreciseType。此类B扩展了A的特定版本,但A的参数不依赖于PreciseType

如果要创建具有在父类规范中使用的参数的泛型类,可以使用以下命令:

class B <PreciseType> extends A <PreciseType>{}
相关问题