Processing Advanced Intro #01 | Object-Oriented Programing
Contents
- What’s OOP?
- Outline
- Class
- Practice
- RandomWalker
What’s OOP?
Outline
Object-Oriented Programing (OOP) is one of the method for programing. The one we used in previous tutorial is Procedural Programing (PP). OOP is the method to define “object” which has several “properties” and “behaviors” in contrast to PP is the method to make workflow with variables and functions.
These two codes are examples showing difference between OOP and PP.
PP
int x,y,r; void setup(){ size(200,200); x = 100; y = 80; r = 20; } void draw(){ background(0); ellipse(x,y,r,r); }
OOP
class Circle{ int x,y,r; Circle(int _x, int _y, int _r){ x = _x; y = _y; r = _r; } void show(){ ellipse(x,y,r,r); } } Circle c; void setup(){ size(200,200); c = new Circle(100,80,20); } void draw(){ background(0); c.show(); }
Class
Class is used for defining “objects”. Class is consisted of 3 elements – property variable, method, constructor. Property variables are used for defining properties of the object, method for behavior, and constructor is for initialization.
class Circle{ int x,y,r; Circle(int _x, int _y, int _r){ x = _x; y = _y; r = _r; } void show(){ ellipse(x,y,r,r); } }
Practice
RandomWalker
Thinking about objects which walks randomly, we can figure out that it needs following properties and behaviors.
- Property
- position
- Step size
- Behavior
- walk
- show
//difining object class RandomWalker { //property variables PVector pos; int step; //constructor RandomWalker(PVector _pos, int _step) { pos = _pos; step = _step; } //methods void walk(){ PVector vec = PVector.random2D(); vec.mult(step); pos.add(vec); } void show() { strokeWeight(5); point(pos.x, pos.y); } } RandomWalker w; void setup() { size(200, 200); //initializing object w = new RandomWalker(new PVector(100,100), 5); } void draw() { background(255); //call object's behavior w.walk(); w.show(); }