04.04.2013 Views

Processing: Creative Coding and Computational Art

Processing: Creative Coding and Computational Art

Processing: Creative Coding and Computational Art

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

forced to literally implement the interface—meaning add curly braces <strong>and</strong> fill in the body<br />

of the method. Next, I’ll add a launchArrow(Archer a) method to the Engine class, which<br />

includes a parameter of the Archer interface type. Here’s the completed Engine class:<br />

class Engine{<br />

void addCreature(Creature c){<br />

c.castSpell();<br />

}<br />

void launchArrow(Archer a){<br />

a.shoot();<br />

}<br />

}<br />

The launchArrow() method works the same way as the addCreature() method. When the<br />

launchArrow() method is called, the respective shoot() method implementation (in a<br />

class implementing the Archer interface) will be selected based on what specific type the<br />

more general Archer types evaluate to. Finally, here’s the updated setup() function,<br />

including the new Knight instantiation <strong>and</strong> launchArrow() method calls:<br />

void setup(){<br />

Creature c = new Creature();<br />

Ogre o = new Ogre();<br />

Elf e = new Elf();<br />

Knight k = new Knight();<br />

Engine eng = new Engine();<br />

eng.addCreature(c);<br />

eng.addCreature(o);<br />

eng.addCreature(e);<br />

eng.launchArrow(e);<br />

eng.launchArrow(k);<br />

}<br />

I want to make one final modification to this example. In the setup() function, I originally<br />

instantiated the Creature object only to help illustrate how method implementations can<br />

be dynamically selected, based on the type of the passed argument. When I passed in a<br />

subclass object, its castSpell() implementation was used, but when I passed in the superclass<br />

object, the castSpell() implementation within the superclass was actually used. In<br />

reality, you generally wouldn’t want to instantiate a Creature object. Instead, you’re only<br />

interested in using the Creature class as a base for more specific creatures.<br />

Java includes the reserved keyword abstract, which can be used to enforce this behavior.<br />

You simply preface the class declaration with the abstract keyword, turning the class into<br />

an abstract class. Here’s the Creature class as an abstract class:<br />

abstract class Creature{<br />

void castSpell(){<br />

println("nothing to say");<br />

}<br />

}<br />

OBJECT-ORIENTED PROGRAMMING<br />

333<br />

8

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!