Wednesday 9 May 2018

Why should a private constructor throw an exception?

One of my friend got this interview question. Interviewer asked him that a class  ‘X’ has only one constructor, and it is throwing exception like below.

class X{
 
 private X() {
  throw new IllegalStateException("No instances!");
 }

        ...
 ...
}

Interviewer asked him, tell me the situation, where can I use above kind of class?

Why the constructor is private?
If you do not want to create an instance of class from outside, you can make the constructor private. But if you do not throw an exception from the constructor, the code inside the class X, can create an instance of the class.
class X{
 
 private X() {
  
 }
 
 public static X getInstance() {
  return new X();
 }
}

You can get an instance of class X, by calling getInstance method.

On what cases the constructor should throw an exception?
Suppose if a class has only static methods, then no point in creating an object to that class. You can always use the class name to access the static methods. By throwing an exception, we can prevent accidental invocation of the constructor from within the class.

This scenario make sense for the classes java.lang.Math, java.util.Arrays. These classes has only static methods.


You may like


No comments:

Post a Comment