View Full Version : How to access new methods from a list?
john.hunt
01-19-2007, 02:59 PM
I define some new methods for an object. In my case, I add "march" to ToySolder. I then build a list of toy solders which I want to march. Of course I can't call the march method from the list because once on the list my item are no longer ToySolder but "Object" which don't know about the method. So how to get around this? I guess what I would like is a cast operator but I can't seem to find one.
lanceA
01-19-2007, 04:39 PM
The exercise in the book uses a For all together and a list variable, named platoon, to get the soldiers to march. Try that.
john.hunt
01-20-2007, 11:56 AM
I am using Alice in Action by Joel Adams.
I don't see an example with solders.
lanceA
01-20-2007, 12:38 PM
Sorry. . . try looking on page 167 in his book. You can do what you want to do with Alice's forAllInOrder statement. He gives an example in his Court of the Fairy Queen program.
john.hunt
01-20-2007, 12:50 PM
Yep, I looked at Adam's court example quite a bit.
He never actually invokes a method that does not belong to the base Object.
He gets sub parts using the partNamed command, but those in turn only support the base object methods.
I could get around my problem by moving all of the underlying actions such as rightLeg.turn(FORWARD) out of march and putting them directly into the loop. Eventually everything I put in march comes down to actions supported by objects plus control structures.
However, this completely breaks the encapsulation. If my primary goal was to do pretty things this would be ok. But, in my case the primary goal is to teach OO programming. So breaking the encapsulation sortof defeats the purpose.
lanceA
01-20-2007, 01:08 PM
I concur with the OOP statement, unfortunately I'm not sure how to preserve encapsulation without doing it in the manner he shows using the tools available in Alice. Good luck and I would be interested in how you solve this.
lanceA
01-20-2007, 04:05 PM
I doubt this has any bearing on what you are trying to accomplish, but with Java 5 and it's Generics, casting of objects is no longer required. i.e.,
List<soldiers> army = new LinkedList<soldiers>();
To use an object from the List you no longer have to cast.
I would still be interested in how you solve this. Good luck :)
By the way, Adams has a new book out:
"Alice In Action With Java"
It starts at the beginner level and takes the user to AP CS1. It 'switches' back and forth between Alice and Java. (This one's 640 pages -- if you live in Afghanistan page counts might mean something. :))
john.hunt
01-22-2007, 07:39 AM
Yep, I can do it in Java. Either with a cast or with the Generics. Or if I was really pressed I could write a custom implementation of a list for my particular data item. The problem is doing it with Alice.