Recently I’ve faced a question : How to avoid instantiating a Java class?
However, I answered by saying:
-
If you don’t want to instantiate a class, use “abstract” modifier. Ex: javax.servlet.HttpServlet, is declared as abstract(though none of its methods are abstract) to avoid instantiation.
-
Declare a no argument private constructor.
Now my question is
a) are there any other ways?
b) why does any one do not want to instantiate a class? – after searching in SO, I got to know from this that Util classes can be made not to instantiate. Any other places where we don’t want to instantiate a class in OOP?
Four reasons spring to mind:
As an example of (2), you may want to create canonical objects. For example, RGB color combinations. You don’t want to create more than one instance of any RGB combo so you do this:
Note: no no-arg constructor is required because another constructor is explicitly defined.