bcorso
bcorso

Reputation: 47068

Instantiation of inner class of another class

I have the following setup which I would think would work but is giving an error in my 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
    }
}

The specific IDE error is:

cannot resolve symbol MyNestedClass1

Upvotes: 0

Views: 54

Answers (3)

Mapsy
Mapsy

Reputation: 4262

You could define the nested class as static. This would allow instantiation independently of a 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();
    }
}

Upvotes: 1

Vibhor Bhardwaj
Vibhor Bhardwaj

Reputation: 3091

// 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
    }
}

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279910

The notation is

MY_CLASS1.new MyNestedClass1(); //No Error

Syntax is

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

Upvotes: 2

Related Questions