Osion kuvaus

  • Basics of Object-Oriented Programming (OOP)

    First some definitions:

    • Objects are collections of functions (often called methods) and variables (often called attributes or fields). In other words, things that belong together are encapsulated into an object.
    • Classes are object descriptions, which you then turn into individual objects (often called instances).
    • Constructor is a required method that gets called when the object is created with the keyword new. Much like setup in Processing, it is meant for setting initial values for the attributes and doing other initial tasks.

    We have actually been using objects before. PImage and PFont are two such examples. Both of them are logical wholes of things that belong together, much more complex than just simple variables.

    Let's see an example: simpleoop.pde

    The constructor has the same name as the class. It often takes parameters that are used when setting up a new object in a particular way. At times there's collision between the parameter names and the internal attributes of the class, which can be solved using the keyword this:

    class MyClass
      int a;
      MyClass(int a) // This is the constructor
        this.a=a; // "this" refers to the object itself

    Just like with simple variables, there can be arrays of objects, and they can be passed as parameters to functions when necessary. There are many other things that go with objects, such as inheritance and protecting attributes from external access, but we'll look more into those on the From Data to Pixels course.


    Create a class called Cat, which contains the following functionality:

    • A constructor that lets us set the initial place of the cat at (x,y)
    • A paint method (function) that draws the cat at its current location
    • An update method that makes the cat move toward the mouse if it's not there already

    Make two cats with the names duchess and thomas with different starting locations and make them follow the mouse pointer by calling their update() and paint() each frame. This might be a good opportunity to use PImage for a little prettier graphics than mine:


    Example solución: cats.pde