How to enforce non-instantiability in a class in Java

Overview

Sometimes, developers need to enforce non-instantiability to a class, i.e., so class objects cannot be instantiatedcreated.

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.

Method

We can make a class non-instantiable by making the constructor of the class private. By making the constructor private, the following happens:

  1. The constructor becomes inaccessible outside the class, so class objects can’t be created.
  2. The class can’t be made a parent class by extending it, as the constructor can’t be called from the subclass.

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.

Main.java
Student.java
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");
    }
}