gpt4 book ai didi

java - 在 Java 中使用泛型编程,就像这样 : class A, 为什么我不能 new B 的对象

转载 作者:行者123 更新时间:2023-12-01 18:51:58 25 4
gpt4 key购买 nike

public class A<B> {
public func() {
B b = new B();
}
}

我从 Netbeans 收到此错误提示:

unexpected type
required: class
found: type parameter B
where Bis a type-variable:
B extends Object declared in class A

如何新建 B 类对象?

最佳答案

BA<B>只是一个类型参数。您无法创建实例化参数。您只能创建实际类型的实例。

但是您可以声明将该实例作为参数的方法 public func(B b) .

我建议您阅读 generics 上的教程.

关于java - 在 Java 中使用泛型编程,就像这样 : class A<B>, 为什么我不能 new B 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15594605/

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