When we try to instantiate an Inner class (aka: non-static Nested class) in java, say we do that in two cases:
1.in a main method in the same file of the outer Class in which we have two options: (ex:)
public class Test1 { class InnerClass { } public static void main(String[] args) { InnerClass inner = new Test1().new InnerClass(); } } or :
public class Test1 { class InnerClass { } public static void main(String[] args) { Test1.InnerClass inner = new Test1().new InnerClass(); } } - In a another class (say different file), then we have the second option only and using the first option requires us (of course) to import the InnerClass..,
Q: could you please explain why do we have the first option (without any import required) in the first case (the main method in the same file)?
Edit:
I guess the answer to the first question is some how related to the core idea of inner classes. but then +Q:
Q: Isn't an inner class a regular-member of an outer class, so if the inner class is not declared static (static nested class) then I suppose it is a non-static member and consequently its reference type, so why are we able to declare it within a static context (static method) ?
new InnerClass(), it's on an instance variable retrieved vianew Test1(). When you assign toTest1.InnerClass(vs justInnerClass, since that's the only difference I'm seeing), there's really no restrictions there. You can even use the FQN if you want:my.random.package.Test1.InnerClass var = /* etc */;newis allowed in all contexts. Once you've created an instance, and you invoke via that instance, you aren't invoking from a static context, you're invoking from the context of that instance. Think about it, if you couldn't do that, you wouldn't be able to run any program, ever.