I have an abstract class that defines the structure of a scoreitem to be drawn in a graphic. There are multiple variants of the score items. They all have the same instance variables, but each has its own drawing implementation which is quite large and complex. These drawing implementations consist mainly of goniometric calculations and do hardly share any code.
In order to keep the code readable, I want to use a subclass for each variant. In the subclass I will define the drawing method implementation. See simplified example below.
abstract class ScoreItem {
int score;
Color color;
...
abstract void draw();
public class RadarItem extends ScoreItem {
@Override
public void draw() {
// RADAR IMPLEMENTATION
...
}
}
public class LineItem extends ScoreItem {
@Override
public void draw() {
// LINE IMPLEMENTATION
...
}
}
etc.
}
Now, I want to use a Graphic class in which I have a list of ScoreItems. The list can contain different variants of the abstract ScoreItem, and the class must loop over the ScoreItems in order to draw them, like below:
public class Graphic {
...
public void generate() {
List<ScoreItem> scoreItems = ...;
for (ScoreItem scoreItem : scoreItems) { scoreItem.draw(); }
}
}
Now this should work; I tested it in a simple test project. However, where I'm running into problems; the Graphic class must be serialized and I'm getting into trouble with the deserialization. This doesn't work (java.lang.RuntimeException: "class" field not found for abstract class). I assume GSON cannot deserialize into the abstract class. When I change the ScoreItem class into a regular class, obviously GSON deserialization works, but then I can't use the draw() method on the subclasses.
I hope I have described the problem adequately and consisely enough. Maybe it's just not good pracice to use a List with different object types. Any solutions or recommendations are greatly appreciated.
With the answers nudging me in the right direction, the solution was to use an GSON Interface Adapter (changed to an Abstract Adapter).
As described here.