gpt4 book ai didi

java - 继承通用类型并强制

转载 作者:行者123 更新时间:2023-11-29 05:50:03 25 4
gpt4 key购买 nike

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

类似于:

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

或者:

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

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

最佳答案

给定

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仔细并多次掌握它们。

关于java - 继承通用类型并强制 <type>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14259600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com