I have an abstract super class with 40 attributes. I also have 2 subclasses that basically extend the super class. Now I want to convert one child class with another.
public abstract class ParentClass{
// ... many attributes
}
public ChildClassA extends ParentClass{}
public ChildClassB extends ParentClass{}
A simple class cast like this is not working and throws ClassCastException:
public ChildClassA to(){
return (ChildClassA) ((ParentClass) this);
}
I could manually write a copy constructor but its tedious work.
Another approach is to serialize and convert. For example using XML or JSON. But that is used for cloning a class and again deserializing would throw class cast exception.
Is there are any other better ways?
EDIT:
Since people have asked for design decision:
I have 2 tables of identical columns. One table has data and the other one doesn't. I have to retrieve rows from original table -> do processing -> put back in second table.
So to minimize code complexity I have super class entity (JPA) which has all the fields (more than 40 fields, annotated with`) and have 2 subclasses extending from it (because I can only have 1 @Table annotation per class).
Now to do processing I need to retrieve data from original table to original sub class. Create a new second subclass and copy values from original to new. Do processing. Persist 2nd entity onto 2nd table.
I would question the design decision of extending the base class with subclasses that don't add anything, especially since they have to be converted from one to another. You could use one class instead, but add an enum field that differentiates the types from one another. Then the conversion would be simply changing this field to a different value.
However, if you really need them to be different classes and be able to convert from one to another, and you don't want to write tedious code to copy fields manually, you could look up some Java mapping frameworks, like MapStruct.