gpt4 book ai didi

java - Java 中的继承、泛型和转换

转载 作者:行者123 更新时间:2023-12-02 08:33:20 27 4
gpt4 key购买 nike

我有两个类,它们都扩展了Example

public class ClassA extends Example {

public ClassA() {
super("a", "class");
}
...
}

public class ClassB extends Example {

public ClassB() {
super("b", "class");
}
...
}

public class Example () {

public String get(String x, String y) {
return "Hello";
}
}

那就这样吧,一切都很好。假设我们有另一个类,名为ExampleManager。对于示例管理器,我想使用泛型类型并因此返回该泛型类型。例如

public class ExampleManager<T extends Example> {

public T getExample() {
return new T("example","example"); // So what exactly goes here?
}
}

那么,在我返回泛型类型的地方,如何才能使其真正正常工作并将 Example 转换为 classAclassB

非常感谢

最佳答案

您不能使用泛型类型来实例化新对象(即您不能执行new T(params))。

关于java - Java 中的继承、泛型和转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2648758/

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