非静态内部类对象的创建,没有显式的封装实例

问题描述 投票:3回答:1

我读到没有外部类的实例就无法创建内部类的实例。但是,当我尝试使用内部类的实例作为外部类的实例成员来创建其实例时,它就起作用了。

我知道它是通过对我的外部类对象的引用创建一个内部对象,但这是正确的方法吗?

下面是我的代码段:

public class TestInner {
    private Nonstatic non = null;
    private static int access = 4;

    public class Nonstatic {
        void hello() {
            access = 90; 
        }
    }

    public static void main(String[] args) {
        TestInner outer = new TestInner();
        TestInner.Nonstatic innern= outer.new Nonstatic();
        System.out.println("Non static obj1 is "+innern);

        outer.testinnerObj();
    }

    public void testinnerObj() {
        non = new Nonstatic(); 
        System.out.println("Non static obj2 is "+non);
        non.hello();
    }
}
java inner-classes
1个回答
2
投票

您正在编写“如果没有外部类实例,则无法创建内部类实例”。这就是您正在做的。

首先,您创建“外部”类的实例:

TestInner outer = new TestInner();

然后,您创建“内部”类的实例-它仅存在在外部范围内:TestInner.Nonstatic innern= outer.new Nonstatic();

因此,问题可能归结为:是的,您正在静态main方法中创建对象。但这无关紧要,因为您使用的语法outer.new在外部范围内创建它。

希望有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.