实例化另一个类的内部类

时间:2014-09-02 01:53:45

标签: java android static inner-classes non-static

我有以下设置,我认为可以使用但在我的IDE(Android Studio)中出错:

// MyClass1.java
public class MyClass1{
    public MyClass1(){}
    public class MyNestedClass1{}
}

// MyClass2.java
public class MyClass2{
    public static MyClass1 MY_CLASS1 = new MyClass1();
    public MyClass2(){
        new MY_CLASS1.MyNestedClass1(); //Error
    }
}

具体的IDE错误是:

  

无法解析符号MyNestedClass1

3 个答案:

答案 0 :(得分:2)

符号是

MY_CLASS1.new MyNestedClass1(); //No Error

语法是

<Expression that resolves to a reference of the enclosing class>.new [Name of nested inner class](..)

答案 1 :(得分:1)

// MyClass2.java
public class MyClass2{
    public static MyClass1 MY_CLASS1 = new MyClass1();//you have already instantiated MyClass1 by new operator here
    public MyClass2(){
        MY_CLASS1.new MyNestedClass1(); //so now intantiate only inner class by new operator
    }
}

答案 2 :(得分:1)

您可以将嵌套类定义为static。这将允许实例化独立于 MyClass1

// MyClass1.java
public class MyClass1{
    public MyClass1(){}
    public static class MyNestedClass1{}
}

// MyClass2.java
public class MyClass2{
    public MyClass2(){
        /* One Way. */
        new MyClass1.MyNestedClass1();
        /* Or Another. */
        new MyNestedClass1();
    }
}