Processing OOP Examples

4.564 | Tutorials and Samples (Processing)
write requests to: takehiko@mit.edu
original: 09/02/02 last revised : 09/02/02

Example 1


// First, create a class to describe an cat generally. We name the class as CAT.
// Each cat always has a unique position, so we define CAT with two instance variables to hold coordinates.
// Their values will be specified when each cat (an unique instance of CAT) is made.
class CAT { // CAT is the name of the class. It has two instance variables.
int x_pos; // Each cat assigns x_pos with a unique integer value.
int y_pos;
}
// When we make specific cats, we identify each of them by holding it in a variable.
// The following line declares that corbu and mies are variables that will hold each CAT object.
CAT corbu, mies;
void setup() {
corbu = new CAT (); // This actually creates a CAT object (an instance of cat).
corbu.x_pos = 10; // Use dot notation to access instance variable.
corbu.y_pos = 20;
mies = new CAT ();
mies.x_pos = 20;
mies.y_pos = 60;
size(400,80);
}
void draw() {
background(100);
corbu.x_pos = corbu.x_pos + 1;
ellipse(corbu.x_pos, corbu.y_pos, 20, 20);
mies.x_pos = mies.x_pos + 1;
ellipse(mies.x_pos, mies.y_pos, 20, 20);
}



Example 2

// In OOP, you can also define a method (function) that works specifically for an object of the class.
// The variables without dot notation can be interpreted in the context of class instance.
class CAT {
int x_pos;
int y_pos;
void display() { // Each cat will use this function.
x_pos = x_pos + 1; // This refers x_pos of an instance of CAT (no dot sytax needed)
ellipse(x_pos, y_pos, 20, 20);
}
}
CAT corbu, mies;
void setup() {
corbu = new CAT ();
corbu.x_pos = 10;
corbu.y_pos = 20;
mies = new CAT ();
mies.x_pos = 20;
mies.y_pos = 60;
size(400,80);
}
void draw() {
background(100);
corbu.display(); // Use dot notation to access method of the class.
mies.display();
}
Example 3


class CAT {
int x_pos;
int y_pos;
// Constructor defines how an instance is initializes when new command creates it.
// It can employ arguments much like a method, but without return value type in front.
CAT(int initial_x, int initial_y) {
x_pos = initial_x;
y_pos = initial_y;
}
void display() {
if (x_pos < 400) { x_pos = x_pos + 1;}
else {x_pos = 0;}
ellipse(x_pos, y_pos, 20, 20);
}
}
CAT corbu, mies;
void setup() {
corbu = new CAT (10, 20); // new CAT takes two arguments as its constructor defined above
mies = new CAT (120, 60);
size(400,80);
}
void draw() {
background(100);
corbu.display();
mies.display();
}

Education | Research | Who we are | Gallery | Bookmarks

Copyright © 1996 Takehiko Nagakura
Massachusetts Institute of Technology