views:

114

answers:

2

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?

+7  A: 

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 as abstract, 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.

Stephen C
Within your private constructor, you could throw a new AssertionError with the message "don't instantiate" to make your wishes even more explicit.
ILMTitan
That is a runtime solution. The OP wants a compile time solution.
Stephen C
A: 

Restructure it and make it an anonymous class.

Romain Hippeau