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.

Inheritance in Java is absolutely fundamental to the language’s design. In fact, every class<br />

in Java except the Object class has at a minimum one superclass, <strong>and</strong> every class except<br />

the Object class has a lineage that goes back to Object. For example, when you export a<br />

<strong>Processing</strong> sketch, a Java applet is created. Here is the Applet class’s lineage:<br />

java.lang.Object<br />

java.awt.Component<br />

java.awt.Container<br />

java.awt.Panel<br />

java.applet.Applet<br />

The classes are the words that start with an initial cap (Object, Component, Container,<br />

Panel, <strong>and</strong> Applet). The words connected to them by a dot are the packages the classes<br />

live in. Packages are just directories or folders that hold class files. In this lineage, Applet<br />

inherits from Panel, which inherits from Container, which inherits from Component, which<br />

inherits from Object. Therefore, the Applet class has access to all the accessible properties<br />

<strong>and</strong> methods declared within its own class <strong>and</strong> from all the classes above it—giving the<br />

Applet class access to over 200 methods. However, the inheritance chain doesn’t go the<br />

other way. Object doesn’t have access to any properties or methods besides those<br />

declared within its own class description, as it is at the top of the inheritance chain for all<br />

classes. On the other h<strong>and</strong>, the Panel class has access to methods/properties in<br />

Container, Component, <strong>and</strong> Object—but not Applet.<br />

Applying inheritance<br />

Using inheritance is pretty straightforward. In the following example, I have a very simple<br />

Shape class <strong>and</strong> Polygon class. The Polygon class inherits from (or extends) the Shape class.<br />

class Shape {<br />

//class properties<br />

int x;<br />

int y;<br />

int w;<br />

int h;<br />

//constructors<br />

Shape (){<br />

}<br />

Shape (int x, int y, int w, int h){<br />

this.x = x;<br />

this.y = y;<br />

this.w = w;<br />

this.h = h;<br />

}<br />

}<br />

class Polygon extends Shape{<br />

int pts;<br />

//constructor<br />

OBJECT-ORIENTED PROGRAMMING<br />

321<br />

8

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

Saved successfully!

Ooh no, something went wrong!