Reputation: 65
I have one class (class util) for generating password(it has only one public static method ). Here two ways are : To make it abstract so no one can create its instance
public abstract class PasswordGenerator {
public static String randomstring(int lo, int hi) {
// Some logic , doesn't matter
return "";
}
}
or to make its constructor private
. So What's the best approach to do that ?
public class PasswordGenerator {
private PasswordGenerator() {
}
public static String randomstring(int lo, int hi) {
// Some logic , doesn't matter
return "";
}
}
So What's the best approach to do that ?
Upvotes: 0
Views: 57
Reputation: 4091
Make both the class final
and the constructor private
.
With the final
keyword you clearly express the intent that the class is not made to be inherited.
With the private
constructor you clearly express the intent that the class is not made to be instanciated.
public final class PasswordGenerator {
private PasswordGenerator() {}
public static String randomstring(int lo, int hi) {
// Some logic , doesn't matter
return "";
}
}
Upvotes: 1
Reputation: 1091
You should definitely not make the class abstract, as this might indicate to other developers, that it is intended to be extended (and therefor instantiated).
Having a class technically being able to be instantiated is a minor problem.
But in this SO thread you can see a workaround, that uses a private constructor in combination with making the class final.
Upvotes: 3