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.

PROCESSING: CREATIVE CODING AND COMPUTATIONAL ART<br />

332<br />

Returning to the creature engine example, let’s say some of the creatures have archery<br />

capabilities. It would be possible to add archery capabilities directly within the Creature<br />

class (which each class extends), but of course not all creatures would be archers, so it<br />

really doesn’t belong in the Creature superclass. Another possible option might be to<br />

create a new Archer class, but the problem there is that you’re not allowed to have a class<br />

in <strong>Processing</strong>/Java extend more than one class. Since each creature needs to extend the<br />

Creature class, it wouldn’t be possible to also extend the Archer class. Using an interface<br />

can help solve this problem. As discussed, an interface can only include constants <strong>and</strong><br />

unimplemented methods (method signatures). Here’s a very simple Archer interface:<br />

interface Archer{<br />

void shoot();<br />

}<br />

This interface only includes a shoot() method; notice the absence of curly braces following<br />

the shoot() method signature. To use the interface, you need to add the implements<br />

keyword along with the interface name to the end of another class declaration. I’ll add the<br />

interface to the Elf class <strong>and</strong> also to a new Knight class. Here’s what the class declaration<br />

statements look like:<br />

class Elf extends Creature implements Archer<br />

class Knight extends Creature implements Archer<br />

And here are the completed Elf <strong>and</strong> Knight classes:<br />

// Elf class<br />

class Elf extends Creature implements Archer{<br />

void castSpell(){<br />

println("Gotta make the cookies");<br />

}<br />

// required method from interface<br />

void shoot(){<br />

println("Elf shoots");<br />

}<br />

}<br />

//Knight class<br />

class Knight extends Creature implements Archer{<br />

void castSpell(){<br />

println("Mirror, mirror on thw wall...");<br />

}<br />

// required method from interface<br />

void shoot(){<br />

println("Knight shoots");<br />

}<br />

}<br />

Notice that both classes contain the shoot() method, including their own unique implementations.<br />

It’s important to remember that any class that implements an interface is

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

Saved successfully!

Ooh no, something went wrong!