Is it possible to restrict creation of inner class...
# announcements
p
Is it possible to restrict creation of inner class objects to the outer class, so that other classes can’t do new innerObject = OuterClass.InnerClass()
n
Perhaps
sealed
is what you're looking for
a
You can make the inner class private (But then you can't expose the type, so if you want to do that then you need to use an interface I guess)
t
If you don't need the inner class to be visible to other classes, make it private. Otherwise, make the inner class's constructor private so that only its containing class can instantiate it :
Copy code
class Outer {
    inner class Inner private constructor() {
        [...]
    }
}
p
If I make the constructor private how can I create it in the outer class?
a
Yea afaict you can't so I think only option is exposing an interface and make the inner implement it But maybe there's another way