I have the following scenario:
class Parent {}
class Child1 extends Parent {}
class Child2 extends Parent {}
interface ExternalSystem {
Parent materialize(Parent a)
}
class Child1System implements ExternalSystem {
Parent materialize(Parent a) {
// specialize a and convert it into Child1
}
}
class Child2System implements ExternalSystem {
Parent materialize(Parent a) {
// specialize a and convert it into Child2
}
}
I want to let users create objects of type Parent. Some components of the system are OK with the information that Parent provides. At some point though, I want to materialize these objects in an external system and depending on which ExternalSystem implementation I call, Parent objects should now be specialized objects.
Is there a way of creating a new child object and replace the space used by the parent object?
I can’t just replace Parent a object with a new object of type Child1 or Child1 because a could have been referenced in other places. So, essentially, what I want is all references to keep looking at Parent a but instead of a being of type Parent it will now be of a child type.
Alternatively, can this be designed differently?
There is no placement new feature in Java. By definition of managed heap.
The only thing that you can do is to create proxy object that implements ExternalSystem. That proxy will dispatch calls to instances of child1 or child2.