selects the factory method of if it's present over the constructor. Seems harmless until you you have a hierarchy of classes/interfaces in which some of them define the method of. I was surprised when I got ClassCastException because the factory method in the super interface returned an instance of a different type:
interface Super {
static Super of(String s) {
// return either new A, or new B
}
}
record A(String s) implements Super {}
record B(String s) implements Super {}
Is it more sensible to prefer the constructor when present over the factory method? The constructor is guaranteed to return an instance of the same type.
The following line:
selects the factory method
of
if it's present over the constructor. Seems harmless until you you have a hierarchy of classes/interfaces in which some of them define the methodof
. I was surprised when I gotClassCastException
because the factory method in the super interface returned an instance of a different type:Is it more sensible to prefer the constructor when present over the factory method? The constructor is guaranteed to return an instance of the same type.