Create instance of non-static inner class from outside

suggest change

An inner class that is visible to another class can be instantiated from that class. The inner class here is package-private, so OutsideClass must be in the same package.

The inner class depends on the outer class and requires a reference to an instance of it. To create an instance of the inner class, call new on an instance of the outer class.

class OuterClass {

    class InnerClass {
    }
}

class OutsideClass {

    OuterClass outer = new OuterClass();
    
    OuterClass.InnerClass createInner() {
        return outer.new InnerClass();
    }
}

Note the outer.new syntax.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents