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 />

684<br />

Example 3: Using <strong>Processing</strong>’s append() function on an<br />

array of objects<br />

// type casting required<br />

void setup(){<br />

SimpleClass[] sc = {new SimpleClass(), new SimpleClass(), ➥<br />

new SimpleClass()};<br />

println("sc length before append = " + sc.length);<br />

// I need to explicitely cast the returned Object array ➥<br />

to a SimpleClass array<br />

sc = ((SimpleClass[])append(sc, new SimpleClass()));<br />

print("sc length after append = " + sc.length);<br />

}<br />

class SimpleClass{}<br />

This third example requires some underst<strong>and</strong>ing of OOP, which is covered in detail in<br />

Chapter 8.<br />

The last line in the example is the definition for a class (which has no capabilities at all, but<br />

is a valid class nonetheless). Since a class is a legal data type, it’s OK for me to declare an<br />

array of type SimpleClass, as I did in this line:<br />

SimpleClass[] sc = {new SimpleClass(), new SimpleClass(), ➥<br />

new SimpleClass()};<br />

I also filled the array with three SimpleClass objects when I declared it. Every time new<br />

SimpleClass() is called, a SimpleClass object is returned between the curly braces. Thus,<br />

the sc array holds three SimpleClass object references. The first println() statement<br />

confirms this. Next, I call <strong>Processing</strong>’s append() function, which is where the type casting<br />

occurs. If I had tried to call the append() function as I did in the previous example—like<br />

this:<br />

sc = append(sc, new SimpleClass());<br />

I’d get an error to the effect that I can’t assign an array of type Object to a variable of<br />

type SimpleClass[]. The reason that the append() function converts the original<br />

SimpleClass[] array to type Object relates to how the append() function works internally,<br />

which I won’t go into. The way to fix this type mismatch is to explicitly type cast the<br />

Object array back to SimpleClass[], as I did in this line:<br />

Control<br />

sc = ((SimpleClass[])append(sc, new SimpleClass()));<br />

The Control section includes 18 entries divided in four sections. Control elements in<br />

Programming are the logic constructs that control how a program flows, as well as, in the<br />

case of loops, the data processing mechanisms supplying power <strong>and</strong> iterative efficiency.

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

Saved successfully!

Ooh no, something went wrong!