Create instance of non-static inner class from outside
suggest changeAn 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents