Java syntax question. I have been writing in this language for a relatively long time. But recently I realized that I did not know how to create an instance of an internal class from the outside, if this class is non-static. For example, I have a class:

class Outer { Outer() { } ... class Inner { Inner() { } ... } } 

How to create an instance of the class Inner from an external class?

    1 answer 1

    As you know, a non-static inner class must be associated with an object of the parent class. If you have such an object, the inner class constructor is called as follows.

     Outer outer = new Outer(); Innter inner = outer.new Inner(); 
    • Exactly, if Outer is not created, then it’s impossible to create a non-static Inner - Barmaley
    • And it will not work? Innter inner = new Outer.Inner (); - AlexAndR
    • @AlexAndR, no, only if the Inner class is static. - Sinitsyn Artyom
    • IMHO, this becomes obvious if you ask yourself: which variables that are in the Outer can the created Inner instance access? If Outer was not created, then these variables simply do not exist . - avp
    • Well, yes, I thought more closely, anyway, the question: "How to address a non-static field without creating a class" is obtained ... - AlexAndR