I sometimes write classes which can be converted to- and from- something else, and I’m used to writing it as a non-static convert-to method and a static convert-from method, for example:
class A {
B toB() {...}
static A fromB(B b) {...}
}
or
class B {
void save(File f) {...}
static B load(File f) {...}
}
I used to think it’s a good and simple approach, but lately the static-ness of the conversion-from method has been annoying me, for instance if I want to define an interface for types that can be converted to- and from- B:
interface ConvertableToAndFromB {
B toB();
// ?
}
So, is there an elegant way of doing that without having the conversion-from as static, other than migrating to Smalltalk?
EDIT
To clarify, I realize I can add a non-static method in the interface, e.g.:
interface ConvertableToAndFromB {
B toB();
void fromB(B b);
}
or, if I want to allow immutable types (thanks Stripling):
interface ConvertableToAndFromB<T implements ConvertibleToAndFromB<T>> {
B toB();
T fromB(B b);
}
But that will require me to create a new A before I can even invoke this, as in:
A a = new A();
a.fromB(b);
or (for immutable):
A a = new A();
a = a.fromB(b);
which is what I’m trying to avoid (but will do with no other solution). I just hope there’s a nicer way.
Often, a fromB method would be implemented as a copy constructor. E.g.
Unfortunately this does not help you create an interface to abstract said functionality. Normally, a separate factory could be used, and this factory implement an interface, but this would still not allow you to get around being able to implement the method in your object in a non-static way while avoiding unnecessary instantiation.