gpt4 book ai didi

java - 创建泛型类的公共(public)内部类的实例

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:53:51 24 4
gpt4 key购买 nike

所以我有如下内容:

public class Enclosing<T extends Comparable<T>> {
// non-relevant code snipped
public class Inner {
private T value;
public Inner(T t) {
value = t;
}
}
}

万物皆可编译,天下皆大欢喜。但是,每当我尝试创建 Enclosing.Inner 的实例时如下,我不行:

new Enclosing<Integer>.Inner(5);

出现以下错误:

Cannot allocate the member type Enclosing<Integer>.Inner using a parameterized compound name; use its simple name and an enclosing instance of type Enclosing<Integer>.

重要的是要注意我不能使内部类static ,因为它包含类型为 T 的字段.

我该如何解决这个问题?

最佳答案

To instantiate an inner class ,你必须先实例化外部类。然后,使用以下语法在外部对象中创建内部对象:

  Enclosing<Integer> outerObject = new Enclosing<Integer>();
Enclosing<Integer>.Inner innerObject = outerObject.new Inner();

丑陋的语法暗示了这种设计中的代码味道。封闭类中可能应该有某种工厂方法(getInner 或其他东西),如果从其封闭类外部使用内部类,则内部类可能应该实现一个公共(public)接口(interface)。

关于java - 创建泛型类的公共(public)内部类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8221088/

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