I have Value-Objects/Beans (only containing members, no logic):
public class Parent {
String first;
String second;
}
Some processing logic returns the “Parent”. I then do some further processing and want to add furtehr fields:
public class ParentAddedMembers extends Parent {
String third;
String fourth;
}
The Problem is, I can NOT downcast from Parent to ParentAddedMembers.
ParentAddedMembers parentAddedMembers = (ParentAddedMembers) parent;
This seems to be invalid.
(From my point of view in this case it would be legal, when downcasting the unassigned, new fields would simply hold nulls. But it seems java does not allow this).
What is the correct solution, if I do not want to copy all fields manually (I could write a copy method that copies the Parent members to a newly created ParentAddedMembers. But this does not work for private fields. Furthermore it will break very easyly if I add/delete membes in parent…)
What is the corret solution for this?
Thanks very much!
Markus
Update:
What I want to achive is. I have a thirdparty Library that returns some Objects Parent (from a search result), but I need to add further fields (metadata) to it. Downcasting, as described would solve the problem easily but does not work. I also can not change the parent as it is from a third party lib.
This only makes sense intuitively because the fields in
ParentandParentAddedMembershave the same names for the fields. You say yourself that having a copy constructor is error prone due to modifications to the fields. Wouldn’t such casting capabilities be too? (What if you changeParent.firsttoParent.param1.)Bottom line is that Java disallows this, because it doesn’t make sense in other cases. You can’t cast a
Vehicleinto aCar. (TheVehicleobject may be aBike.)One option would be to simply do
or, to go the route you explain and do a copy constructor.
You could also solve it using reflection. Then you would be able to loop through all fields of
Parentand assign the fields ofParentAddedMembersbased on the field names. (But using reflection indicates some code smell actually.)