是否有可能在java中的静态类中创建内部类的对象?

时间:2022-01-31 22:49:55

How can I declare an object of an inner class inside a static class in java?

如何在java中的静态类中声明内部类的对象?

public class xyz
{
    static class abc
    {
        ...
        // I want to declare an object of class a here. how can I do this?

    }
    class a
    {
        ...
    }
}

1 个解决方案

#1


2  

Instances of inner classes exist in the context of an instance of the enclosing class. So you must first create an instance of the enclosing class, and from there you can create an instance of the inner class. For example:

内部类的实例存在于封闭类的实例的上下文中。因此,您必须首先创建封闭类的实例,然后可以从中创建内部类的实例。例如:

public class xyz {
    static class abc {
        a member = new xyz().new a();
    }

    class a {
    }
}

More information: Oracle Java Tutorials - Nested Classes

更多信息:Oracle Java教程 - 嵌套类

#1


2  

Instances of inner classes exist in the context of an instance of the enclosing class. So you must first create an instance of the enclosing class, and from there you can create an instance of the inner class. For example:

内部类的实例存在于封闭类的实例的上下文中。因此,您必须首先创建封闭类的实例,然后可以从中创建内部类的实例。例如:

public class xyz {
    static class abc {
        a member = new xyz().new a();
    }

    class a {
    }
}

More information: Oracle Java Tutorials - Nested Classes

更多信息:Oracle Java教程 - 嵌套类