58

Object Oriented - A Simple Class

Let's say we want to draw a robot with blinking eyes. And, let's say the eyes need to blink at different rates. We could draw 2 ellipses and change the fill from white to black. I could use the delay(t) command to make the fill() change every few hundred milliseconds (t). The problem with using delay in the draw loop is that the program code stalls during the delay time and no other code executes until the delay is finished and the draw loop runs the next line of code. Even if we make the eyes into functions the delay() function will still hang us up.

We know that creating functions (also called methods) lets us reuse code to make many pandas or many dice or whatever. What if we could fully encapsulate the function so that it ran whenever and wherever. Programmers use object-oriented (OO) classes for these and many other reasons.


The program above is the simplest example of a class in Processing.

Classes have a declaration class robot{ that includes the variable types to be used internally, x and y.

Classes have a constructor - code that guides the creation or "instantiation" of the object.robot (int xpos, int ypos){x = xpos;y = ypos;}

Classes have one or more methods that determine the behaviour of the object.void drive(int myX, intmyY){ . . . etc

robot myRobot; creates an instance of the robot class.

In setup() myRobot = new robot(320, 240); initializes the object with startup variables. The variable types passed to the object must match the variable types in the class definition. NOTE: classes can have more than one constructor for times when we need to use the object with a different set of variable types. This concept is called overloading. There are other ways that OO classes are different and more useful than what we have experienced so far.

Finally, the dot notation is used to invoke the drive method on the class. myRobot.drive(variables).

This is the simplest example of an OO class for Processing. On the next page we'll see how to use the class over and over.