Preventing a Java class from being instantiated and inherited

A class can’t be both final and abstract. You can prevent instantiation by hiding the constructor, and raising an exception to prevent instantiation via reflection.

That looks like this:

final class MyClass {
    private MyClass() {
        throw new IllegalStateException("Cannot be instantiated"); //some exception

Leave a Comment