【问题标题】:Creating instance of inner class outside the outer class in java [duplicate]在java中创建外部类外部的内部类实例[重复]
【发布时间】:2014-08-21 19:39:20
【问题描述】:

我是 Java 新手。

我的文件A.java 如下所示:

public class A {
    public class B {
        int k;
        public B(int a) { k=a; }
    }
    B sth;
    public A(B b) { sth = b; }
}

在另一个 java 文件中,我正在尝试创建 A 对象调用

anotherMethod(new A(new A.B(5)));

但由于某种原因我收到错误:No enclosing instance of type A is accessible. Must qualify the allocation with an enclosing instance of type A (e.g. x.new B() where x is an instance of A).

有人可以解释我怎样才能做我想做的事吗?我的意思是,我真的不需要创建A 的实例,然后将其设置为sth,然后将A 的实例提供给该方法,还是有其他方法可以做到这一点?

【问题讨论】:

  • B 不依赖于 A,因此将其设为静态 (public static class B) 是有意义的 - 然后您的代码就可以工作了。另见:stackoverflow.com/questions/9560600/…
  • 好吧,我不知道为什么我没有想到使用static,但实际上它是解决方案。谢谢

标签: java class inner-classes


【解决方案1】:

在外部类之外,你可以像这样创建内部类的实例

Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();

你的情况

A a = new A();
A.B b = a.new B(5);

更多详情请阅读Java Nested Classes Official Tutorial

【讨论】:

  • 这在大多数情况下都是极好的建议。 +1。但是,在这种情况下它不起作用,因为A 没有默认构造函数。
【解决方案2】:

在您的示例中,您有一个始终绑定到外部类实例的内部类。

如果您想要的只是为了可读性而嵌套类的一种方式,而不是实例关​​联,那么您需要一个静态内部类。

public class A {
    public static class B {
        int k;
        public B(int a) { k=a; }
    }
    B sth;
    public A(B b) { sth = b; }
}

new A.B(4);

【讨论】:

  • 好吧,我不知道为什么我没有想到使用static,但实际上它是解决方案。谢谢。我会在 9 分钟内接受您的答复,届时我将能够这样做。
【解决方案3】:

那里有趣的谜题。除非您将B 设为静态类,否则实例化A 的唯一方法是将null 传递给构造函数。否则你必须得到一个B的实例,它只能从A的实例中实例化,这需要B的实例来构造...

null 解决方案如下所示:

anotherMethod(new A(new A(null).new B(5)));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 2018-01-19
    • 2013-04-26
    • 1970-01-01
    相关资源
    最近更新 更多