I have a class, Action, that has a method called doAction(). This method exists solely to be overwritten for each new action that I add to an action list called allActions.
public void doAction() {
System.out.println("Overload this method.");
}
The list of actions is being stored in the following list:
public static List<Action> allActions = new ArrayList<Action>();
and added to this list with calls like the following:
allActions.add(
new Action(id){
public void doAction(Word w1, Word w2) {
//perform some action
}
}
);
But this code isn't working for me. When I try to access an overwritten doAction() method from the allActions list, it just performs the default method.
I suspect that the problem is that allActions is a list of Action objects, so perhaps the type is being changed away from the anonymous class when it is being added to the list, and reverting to the default method.
Any ideas on how to maintain a list of different anonymous versions of the Action class? I want to be able to call these different doAction() methods based on the id given to the actions.
By the way, this is my first time encountering anonymous classes. I think I understand the concept, but actually using them is another story.
you are using public void doAction(Word w1, Word w2) but you have public void doAction() in parent. So parent method is not overridden.
You actually are overloading the method doAction(). But I suspect you may have confused the words overload and override.
To overload a method, you use a different quantity or type of parameters. This allows the same method to do different things depending how you call it (i.e. with what parameters).
Information on overloading
To override a method, you use the same quantity and type of parameters, and you are required to return the same type as the overridden (super) method. This allows the same method to do different things depending where you call it (i.e. from a superclass or a subclass).
Information on overriding
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With