I am trying to implement an undo feature by creating a stack of 2 subtypes.
I have a stack of parent type UserEntry holding two child types Assign and RelEntry.
Assign and RelEntry is both classes used to insert values (number and relationship) into a grid table.
There is a method call to insert the values into the table as their respective subtypes for example assignToTable()
and RelEntryToTable()
.
I am trying to use a polymorphic method that can call both of these subtypes from the parent stack eg.
parentStack.assignAndRelEntryToTable();
When making the abstract class for UserEntry I have tried an addToPuzzle()
method which I then implemented in both child classes however when trying to call using
for (UserEntry ue : stack){ puzzle.addToPuzzle(ue) }
The method call requires a method specific to each sub-class. I’ve tried creating a method call for each subclass but the puzzle itself cannot be referenced from the sub-classes.
There are 4 classes working together here: UI, RelEntry, UserEntry, and Assign. I am trying to create them for each loop within the UI class as this contains the puzzle variable.
Advertisement
Answer
If I understand your question correctly, you’re looking for instanceof
. It let’s you check if an object is of given type. Using it you can determine subtype of the UserEntry, cast to desired subtype and call one of your methods accordingly. Something like so:
for (UserEntry ue : stack){ if(ue instanceof Assign){ Assign assign = (Assign) ue; puzzle.assignToTable(assign ); } else if(ue instanceof RelEntry){ RelEntry relEntry = (RelEntry) ue; puzzle.relEntryToTable(relEntry); } }