0

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

3
  • Saying non-static inner is redundant. inner means non-static nested class. Commented Sep 2, 2014 at 1:57
  • Okay, thanks. I changed the title. Commented Sep 2, 2014 at 2:03
  • There is no static class here. Commented Feb 6, 2018 at 6:29

3 Answers 3

2

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](..) 
Sign up to request clarification or add additional context in comments.

4 Comments

Awesome, thanks! I'm sure this is already covered but I did not really find anything or know what term to search for in this situation. Appreciate it!
And as the ugliness of the syntax indicates, this is not something you should be doing. These inner classes should be managed by their containing class.
@Thilo what do you mean by managed? Should I not expose the class directly, and instead instantiate it in the parent class only?
Design advice without seeing the bigger picture is impossible, but as a guideline, no one except the owning instance should create inner class instances.
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 } } 

Comments

1

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

1 Comment

Thanks, but I actually need non-static because I use a member from the outerclass. Sorry, I just left that out of the example to simplify the situation. Still good to know, +1.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.