I want a static inner class that can't be instantiated even by the external class. Right now I just have a documentation that says "Please don't instantiate this object". Can I give a better signal?
I want a static inner class that can't be instantiated even by the external class.
I assume that "external class" really means the enclosing class.
If you don't want to restrict the enclosing class, then making the only constructor of the inner class
private
will have the desired effect.If you also want to restrict the enclosing class, the answer is there is no way to do this. If you declare the inner classes constructor as
private
, the enclosing class can still access it and instantiate it. If you declare the inner class asabstract
, the enclosing class can still declare a subclass and instantiate that class.
However, I would suggest that this (i.e. preventing all instantiation of an inner class) is a pointless exercise. Any non-static declarations in the inner class could not be used in any way, and any static declarations may as well be declared in the enclosing class.
Besides, anything that you do to "prevent" the enclosing class from instantiating the inner class can be circumvented by editing the source file containing the two classes. And even a class with a private
constructor can be instantiated using reflection, if you go about it the right way.