Sometimes, developers need to enforce non-instantiability to a class, i.e., so class objects cannot be
For example, utility classes are classes that contain utility methods where an instance of the class is not needed. Instead, the methods of the class can be made static
so that the methods can be accessed using the class name.
We can make a class non-instantiable by making the constructor of the class private
. By making the constructor private, the following happens:
The code below throws the following error during compilation:
java: Student() has private access in Student
This is because we tried to create a class object where the constructor is private.
public class Student {public String name;private Student(){}}
However, we can change the accessibility of the constructor at run time using reflection
in Java. In order to avoid that, throw an exception in the private constructor.
Modify the Student
class, as shown below:
public class Student {
public String name;
private Student(){
throw new UnsupportedOperationException("Class Instantiation not supported");
}
}