I found this construct in some code.
Is there any benefit to have a private static class implement A? This reminded me of the Pimpl idiom in C++. Is there any benefit to using the Pimpl idiom in Java?
public abstract class A {
public void doStuff();
public static A getNewInstance() {
return new AImpl();
}
private static class AImpl extends A {
public void doStuff() {
....
}
}
}
Well, it hides the implementation away completely, so from an encapsulation point of view it's quite nice. One situation I've seen this in a few times is custom comparators. For example:
There's no real need for the comparator implementation classes to be visible outside
Person
, and it's nice to be able to get an instance easily via the public static field.No callers need to know the implementation - there could just be one comparator class which takes parameters, for example - they just express which comparator they want via the constants. (You could equally use an enum for this, of course.)