// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com
// Example 22-2: Polymorphism
// One array of Shapes
Shape[] shapes = new Shape[30];
void setup() {
size(200,200);
smooth();
for (int i = 0; i < shapes.length; i++ ) {
int r = int(random(2));
// Randomly put either circles or squares in our array
if (r == 0) {
shapes[i] = new Circle(100,100,10,color(random(255),100));
} else {
shapes[i] = new Square(100,100,10);
}
}
}
void draw() {
background(255);
// Jiggle and display all shapes
for (int i = 0; i < shapes.length; i++ ) {
shapes[i].jiggle();
shapes[i].display();
}
}
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com
// Example 22-2: Polymorphism
class Circle extends Shape {
// Inherits all instance variables from parent + adding one
color c;
Circle(float x_, float y_, float r_, color c_) {
super(x_,y_,r_); // Call the parent constructor
c = c_; // Also deal with this new instance variable
}
// Call the parent jiggle, but do some more stuff too
void jiggle() {
super.jiggle();
// The Circle jiggles its size as well as its x,y location.
r += random(-1,1);
r = constrain(r,0,100);
}
// The changeColor() function is unique to the Circle class.
void changeColor() {
c = color(random(255));
}
void display() {
ellipseMode(CENTER);
fill(c);
stroke(0);
ellipse(x,y,r,r);
}
}
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com
// Example 22-2: Polymorphism
class Shape {
float x;
float y;
float r;
Shape(float x_, float y_, float r_) {
x = x_;
y = y_;
r = r_;
}
void jiggle() {
x += random(-1,1);
y += random(-1,1);
}
// A generic shape does not really know how to be displayed.
// This will be overridden in the child classes.
void display() {
point(x,y);
}
}
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com
// Example 22-2: Polymorphism
class Square extends Shape {
// Variables are inherited from the parent.
// We could also add variables unique to the Square class if we so desire
Square(float x_, float y_, float r_) {
// If the parent constructor takes arguments then super() needs to pass in those arguments.
super(x_,y_,r_);
}
// Inherits jiggle() from parent
// The square overrides its parent for display.
void display() {
rectMode(CENTER);
fill(175);
stroke(0);
rect(x,y,r,r);
}
}