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.

The entire SportsGear interface in <strong>Processing</strong> would be:<br />

interface SportsGear{<br />

String getBr<strong>and</strong>Name();<br />

float getUnitCost();<br />

void setUnitCost(float unitCost);<br />

void printWarranty();<br />

}<br />

It’s pretty simple to create interfaces. However, using them is a bit trickier, <strong>and</strong> using them<br />

polymorphically is trickier still. We’ll take it one step at a time. Here’s a Bicycle class that<br />

extends a Vehicle class <strong>and</strong> implements the SportsGear interface (this code is not meant<br />

to be run):<br />

class Bicycle extends Vehicle implements SportsGear{<br />

//instance variables<br />

String br<strong>and</strong>Name;<br />

float unitCost;<br />

// constructor<br />

Bicycle(String br<strong>and</strong>Name, float unitCost){<br />

this.br<strong>and</strong>Name = br<strong>and</strong>Name;<br />

this.unitCost = unitCost;<br />

}<br />

/* We're required to implement all methods<br />

from the SportsGear interface*/<br />

String getBr<strong>and</strong>Name(){<br />

return br<strong>and</strong>Name;<br />

}<br />

float getUnitCost(){<br />

return unitCost;<br />

}<br />

void setUnitCost(float unitCost){<br />

this.unitCost = unitCost;<br />

}<br />

void printWarranty(){<br />

println("Bicycle: full replacement value for 1 year");<br />

}<br />

}<br />

OBJECT-ORIENTED PROGRAMMING<br />

To keep things simple in the example, I didn’t bother adding any properties or methods to<br />

the Vehicle class, or extra properties/methods to the Bicycle class. Instead, the Bicycle<br />

class gets all of its members just by implementing the SportsGear interface. Whenever a<br />

class implements an interface—through the use of the implements keyword—the class<br />

must implement all the methods in the interface, which means that it needs to include all<br />

the method definitions contained within the interface, as well as fill in the method blocks.<br />

This is enforced by the compiler, which will generate an error if it’s not done.<br />

327<br />

8

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

Saved successfully!

Ooh no, something went wrong!