问题
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.
回答1:
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);
}
}
回答2:
I have a hard time understanding your requirements exactly so I am going to be very generic.
Syntax might not be 100% correct but it should give the general idea.
public abstract class UserEntry{
abstract void somCommonMethod();
}
public class RelEntry extends UserEntry{
void someCommonMethod(){
//ownRelEntryLogic
}
}
public class Assign extends UserEntry{
void someCommonMethod(){
//ownAssignLogic
}
}
public Puzzle{
ArrayDeque<UserEntry> stack = new ArrayDeque<>();
public void undoLogic(){
stack.pop().someCommonMethod();
}
public void add(UserEntry anyInstanceOfUserEntry){
stack.push(anyInstanceOfUserEntry);
}
}
}
public class UI{
Puzzle p = new Puzzle();
p.add(new RelEntry());
p.add(new Assign());
}
来源:https://stackoverflow.com/questions/65074638/how-to-extract-information-from-java-stack-as-individual-data-types-and-use-in-m