Say I have an interface Interface
, which only contains getters for various fields. This interface has multiple implementations (say Foo
and Bar
), each of which adds various fields. All these implementations are immutable.
Assume I have an instance interface
of Interface
, and I want to create a copy of this instance which changes one of the fields exposed by Interface
. How can I achieve this without casting interface
to a subtype? I cannot use a Builder class for Interface
because this is an abstract interface.
I believe this problem is a fairly generic OOP problem but here is what the Java code for it would look like:
public interface Interface {
public int getVersion();
}
public class Foo implements Interface {
private final int version;
private final String owner;
public Foo(int version, String owner) {
this.version = version;
this.owner = owner;
}
public int getVersion() {
return version;
}
public String getOwner() {
return owner;
}
public String toString() {
StringBuilder builder = new StringBuilder(owner);
builder.append(" v");
builder.append(version);
return builder.toString();
}
}
public Bar implements Interface {
// similar to Foo
}
and the situation where I want to copy an existing instance:
Interface instance = new Foo(1, "some value");
assertEquals("some value v1", instance.toString());
Parent copy = // create the copy based on instance but updating the version to 2
assertEquals("some value v2", copy.toString());