PFA:008 – Functions Continued, Object Oriented Programming (OOP), Classes

Inspiration

Artists

Functions

Below we have created an example of a single raindrop falling down the screen. If I would want to make this single raindrop into multiple raindrops, I would need to create separate arrays for all the variables that are used for a single raindrop.

This is of course possible, but it can get a bit messy fairly quickly. In Processing, we have a better way to do this by combining the functions and the data of a raindrop together.

Object Oriented Programming

Object-oriented programming (OOP) is a programming paradigm that allows you to structure your code in a powerful way. It is not the only way to structure your code, but Java, the language Processing is based on, relies heavily on the concept of OOP.

Objects

Essentially, you can think of objects as collections of data and code. So instead of having to treat these two things as separate in your code, you can package them together using objects.

  • The data in the objects are variables that are often referred to as attributes or fields (I will usually just call them variables)
  • The actual code that tells what the object does, are basically just functions that are part of the object. The functions inside an object are often called methods.
  • Both the variables and the methods are encapsulated into an object

Classes

Classes are object descriptions, which you then turn into individual objects (instances). All classes usually include the following four things:

  1. Name
    • A name that you can decide, usually written with a capital letter.
  2. Data
    • All the variables that this class needs
  3. Constructor
    • A special function inside the class that creates an instance of the object. You can think of it as the setup() function of the class.
    • It always has the same name as the class itself.
    • The constructor is called whenever a new object is created using the keyword new.
    • For example: Particle p = new Particle();
  4. Methods
    • You can create as many methods (functions) inside the class as you need.
// This is an example of a class
// Name:
// This class describes an object called Particle
class Particle{
  // Data: these are the variables (attributes) of the particle
  float x;
  float y;
  float s;
  
  // Constructor:
  // This is the constructor of the class
  Particle(){
    x = random(width);
    y = random(height);
    s = random(1,5);
  }
  
  // Methods:
  // The functions inside the class are methods
  // They are functions that tell what this object should do
  void move(){
  }
  void display(){
  }
  
}

Examples

The example we made in class (11/10/2019):

See more examples from the OOP tips & tricks.