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?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
privatewill 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
privateconstructor can be instantiated using reflection, if you go about it the right way.