I am doing this AntFarm project for my Java class. This project consists of different classes(Food, WorkerAnt, Queen) and they interact with each other using a interface(with a method called process).
http://ljhs.sandi.net/faculty/volger/apajava/GridWorld/Assignments/AntFarm/ - project
I'm currently stuck on the processActors()
method in WorkerAnt
. (It's almost at the bottom of the page.)
The current code is the following:
public void processActors(ArrayList<Actor> actors) {
for (Actor nextActor : actors) {
nextActor.process(this);
}
}
The error I get is the following.
Cannot find symbol symbol: method process(W开发者_JS百科orkerAnt)
Going by the linked assignment, Actor
does not have a process(WorkerAnt)
method.
Instead, this is part of the Processable
interface (and thus Food
).
As such, make sure your Actor
is an Actor
implementing Processable
(for example a Food
).
Ideally you'd change your processActors(ArrayList<Actor> actors)
method to be something like processProcessables(ArrayList<Processable> processables)
.
However, I see in the assignment that you are required to implement a processActors(ArrayList<Actor> actors)
so you can't really do this (although I'm going to call this out as bad design - it's akin to having a method divide(object, object)
instead of divide(double, double)
).
To see why it is bad design, the assignment says
processActors: Each actor in actors needs to call its process method.
Except Actor
s don't have process
methods - Processable
s do, and Actor
s are not Processable
.
In any case, you will have to settle for the fact that you expect some Actor
s to be Processable
s and do something like this:
for(Actor nextActor : actors)
{
if (nextActor instanceof Processable)
((Processable)nextActor).process(this);
}
However, you should have realised this from the assignment:
An Actor could be a QueenAnt, a Cake, a Cookie, or a WorkerAnt. Without the Processable interface, processActors would need to determine the type of actor and then downcast the actor reference before making the call to process. But, since each of these classes implements Processable, processActors only needs to cast the actor to Processable before the call. This polymorphic processing is allowed because Processable contains the process abstract method. The Java Run Time Environment (JRE) determines the actual type of object at runtime and calls the appropriate process method.
精彩评论