在java中创建外部类之外的内部类的实例 [英] Creating instance of inner class outside the outer class in java

查看:324
本文介绍了在java中创建外部类之外的内部类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手。

我的文件 A.java 看起来像这样:

My file A.java looks like this:

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

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

In another java file I'm trying to create the A object calling

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

但由于某种原因我收到错误:没有封闭的A类实例是无障碍。必须使用类型A的封闭实例限定分配(例如,xnew B(),其中x是A的实例。)

but for some reason I get error: 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 然后给出<的实例这个方法的code> A ,还是有其他方法可以做到这一点?

Can someone explain how can I do what I want to do? I mean, do I really nead to create instance of A, then set it's sth and then give the instance of A to the method, or is there another way to do this?

推荐答案

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

In your example you have an inner class that is always tied to an instance of the outer class.

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

If, what you want, is just a way of nesting classes for readability rather than instance association, then you want a static inner class.

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);

这篇关于在java中创建外部类之外的内部类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆