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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

PROCESSING: CREATIVE CODING AND COMPUTATIONAL ART<br />

334<br />

Once a class is declared abstract, the complier will not allow it to be instantiated. So, in the<br />

last example, if I add the abstract keyword in front of the Creature class, I’ll get an error<br />

when I try to run the sketch. However, if I remove the Creature instantiation line as well as<br />

the line below it, where the engine adds the Creature object c, the sketch will run fine.<br />

Besides enforcing this behavior, abstract classes also allow you to add abstract methods to<br />

the class. Abstract methods are simply method declarations (like in interfaces) that also<br />

require the abstract keyword. Here’s an example:<br />

abstract String getCreatureName();<br />

Also similar to interfaces, any class that extends an abstract class must implement all<br />

abstract methods within the superclass. However, unlike interfaces, abstract classes also<br />

allow you to include concrete methods (regular implemented methods) within the class. It<br />

is not necessary for a subclass to reimplement the abstract superclass’s concrete methods,<br />

but of course, as in the example, it can override them. Here’s the completed polymorphism<br />

example, including the Archer interface <strong>and</strong> abstract Creature superclass. I also<br />

added an abstract getCreatureName() method to the Creature superclass, which I then<br />

implemented in each of the (concrete) subclasses.<br />

/* polymorphism example using<br />

inheritance, interface <strong>and</strong><br />

an abstract class */<br />

void setup(){<br />

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

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

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

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

eng.addCreature(o);<br />

eng.addCreature(e);<br />

eng.launchArrow(e);<br />

eng.launchArrow(k);<br />

println(o.getCreatureName());<br />

println(e.getCreatureName());<br />

println(k.getCreatureName());<br />

}<br />

// abstract Creature superclass<br />

abstract class Creature{<br />

/* this method will be overriden by<br />

Creature subclasses */<br />

void castSpell(){<br />

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

}<br />

//abstract getCreatureName method<br />

abstract String getCreatureName();<br />

}

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

Saved successfully!

Ooh no, something went wrong!