How to construct a Non Instantiable AND Non Inheritable Class in Java
Make the constructor private
:
public final class Useless {
private Useless() {}
}
A private constructor is the normal object-oriented solution. However, it would still be possible to instantiate such a class using reflection, like this:
Constructor<Useless> con = Useless.class.getDeclaredConstructor();
con.setAccessible(true); // bypass "private"
Useless object = con.newInstance();
To prevent even reflection from working, throw an exception from the constructor:
public final class Useless {
private Useless() {
throw new UnsupportedOperationException();
}
}
I would use the simplest Singleton pattern
enum Singleton {
INSTANCE;
}
The enum
type is non-instance-able and non-inheritable and the classes initialisation is lazy and thread safe.
To declare there should never be an instance you can also use an enum
enum Utilities {
; // no instances
// add static methods here
}
You mean a class with static methods only? Class cannot be both final and abstract. But you can use private constructor to make it not instantinable.
final class StaticOnly {
private StaticOnly() {
throw new RuntimeException("Do not try to instantiate this");
}
public static String getSomething() {
return "something";
}
}
Below example will work to. You won't instantiate it because it's abstract. You won't inherit it because there is no way to call super constructor from external subclass (only inner subclass will work)
abstract class StaticOnly {
private StaticOnly() {}
public static String getSomething() {
return "something";
}
}
enum will work too
enum StaticOnly {
S;
public static String getSomething() {
return "something";
}
}
but it always have at least one instance (here it's S).