10.1 – Introduction to Objects

Objects

Objects are a new way of thinking about programming. Object Oriented Programming (OOP) places more of an emphasis on modeling real-world behavior.  Objects use everything we have already learned – variables, conditional statements, loops, functions. What’s new is a way of thinking, structuring, and organizing our code.

Think of an object like a noun–> a person, a book, a car, a tree. Think of a human object. A human object has traits- a gender, height, weight, hair color, eye color. A human can also do stuff, like eat, sleep, ride the subway, and exercise.  OOP is a way of combining traits (data) and actions (functionality) into one thing (an object).

The properties or attributes of an object are stored in variables. Take our human example:

Human Attributes
Height (float)
Weight (int)
Gender (boolean)
Name (string)
Age (int) 

The stuff, or actions, an object can do are functions:

Human Functions
Sleep (void sleep(){} )
Eat (void eat(){} )
Exercise (void ugh(){} )
Ride the subway (void tryNotToKillEveryone(){} )

Classes

Objects are created by writing a class. A class is not an object, rather, it is a template for making an object. Think of an object like a cookie, and a class as the cookie cutter. A cookie cutter is not a cookie, it is a template for making a cookie.

Classes are a plan for an object, the general idea of a thing. It has placeholders for details, but it is not ‘made’ yet. It also declares functions that an object could do, but it doesn’t have to (I could go to the gym every day, but I don’t).

You have to plan out the object before you make an object. You write a class before you make an object.

Using an object is the easy part. The hard work goes into writing the object’s class. But, the good news is that you only have to do this once and then can make millions and millions of objects (like using a cookie cutter to make a zillion cookies).

Writing a class

Classes require:

  • Name
  • Data
  • Constructor
  • Methods 

The class name – 

class WhateverYouWantToCallYourClass{
//All of the code for your class is enclosed in these curly brackets
}

*Note the capitalized first letter (and lack of parenthesis). This is why we name variables and functions with a lower case letter so that Capital Class Stands Out

Data– A collection of variables that describe the attributes of your object. In our human example, this would be the height, weight, gender, etc.  They are often referred to as instance variables since each instance of an object contains this set of variables. Think of these as the “global” variables for your class. 

Constructor – A special function inside of a class that creates the instance of the object itself. Think of it like your class’s setup(). It has the same name as the class (including the capital first letter) and it is called ONCE (just like setup)

Methods – These are the functions that create the “actions” that your object can perform. They’re just like the functions we’ve been working with for  a few weeks now.

An example of a car class:

class Car{ //note the Capital C, and lack of ()

//Class's data, just like global variables at the top of your sketch
color c;
int xpos;
int ypos;
int xpseed;

Car(){ //The Constructor, same name as my class, works just like setup
c = color(175);
 xpos = width/2;
 ypos = height/2;
 xspeed = 1;
}

void display(){ //Methods, same old functions!
//display my car
fill(c);
rect(xpos, ypos, 20, 20);
}

void moveCar(){
xpos = xpos + speed;
}

} //the closing bracket for my whole class

A class is a new block of code. It can go anywhere, but typically you put it after draw.

void setup(){

}

void draw(){

}

class Car{ } 

Or better yet, you should create a new tab in Processing. This is done by clicking the right arrow in the top right corner of the Processing window. This brings up a drop down and then you choose New Tab. It will prompt you to enter in the name for the tab. You should name it the same name as your class.

Creating a new tab creates a new .pde file in your sketch folder. This is great because you can reuse your classes in other sketches simply by copying the class.pde file into that sketch.

Using an object

Example of using an object in pseudocode (in this case, a car object):

Data (Global Variables)

Car object.

Setup:
Initialize car object.

Draw:

Fill background. Display car object. Move car object.

Using an object requires 3 steps:
  • Declare an object
  • Initialize an object
  • Call methods on an object

Declaring an object is a lot like declaring a variable. When we declare a variable, we specifiy a data type and a unique name:

int x;

Objects are similar, except the data type isn’t an int, or a float, or a boolean, it’s of whatever type your just defined in your class.

Car myCar; //take note of the Capital C in Car!

Next we initialize our object. We’re used to doing this, too, with variables:

int x; //Declaring a variable

void setup(){
   x = 50; //Initializing the variable
}

Unfortunately since objects are a bit more complex than variables and we need to use a new word: new

//Declare a new object of type Car, called myCar (thats an arbitrary name, just like naming any 'ol variable)
Car myCar;

void setup(){
  //Initialize your car variable
  myCar = new Car();
}

In the above example, “myCar” is the object variable name and “=” indicates we are setting it equal to something, that something being a new instance of a Car object.

Writing new calls your class’s constructor, which is like your class’s setup()

An important note–

When creating a variable, if you forget to initialize your variable, Processing will just default x to 0, boolean’s to false, etc. An object has no default value. If you forget to to initialize an object, Processing will give it the value null, which means nothing. If you encounter the message “NullPointException“, that error is most likely caused by forgetting to initialize an object.

Once we declare and initialize an object, we can call methods on it, aka, use it and invoke the functions that we built into it. You use the “.” operator to access object functions and data

myCar.display();
myCar.drive();

You can use all of the functions you wrote, some, or none (but admittedly that would be a little silly).

Can also access an object’s data attributes–

float x = myCar.xpos;

Putting it all together

Take a look at this non-OOP code that displays a car:

//GLOBAL VARIABLES
color c;
int xpos;
int ypos;
int xspeed;

void setup() {
  size(200, 200);
  c = color(255);
  xpos = width/2;
  ypos = height/2;
  xspeed = 1;
}

void draw() {
  background(0);
  display();
  drive();
}

//FUNCTIONS

void display() {
  rectMode(CENTER);
  fill(c);
  rect(xpos, ypos, 20, 10);
}

void drive() {
  xpos = xpos + xspeed;
  if (xpos > width) {
    xpos = 0;
  }
}

And look at the same code, re-written in OOP:

Car myCar; //Declare a Car object

void setup() {
  size(200, 200); 
  myCar = new Car(); //initialize the car object-- this calls your class' constructor
}

void draw() {
  background(0);
  myCar.display();
  myCar.drive();
  println(myCar.xpos);
}
class Car { //note the CAPITAL C

  //GLOBAL CLASS VARIABLES AKA DATA
  color c;
  float xpos;
  float ypos;
  float xspeed;

  Car() { //CONSTRUCTOR -- think of this like your class's setup
    c = color(255);
    xpos = width/2;
    ypos = height/2;
    xspeed = 1;
  }

  //FUNCTIONALITY
  void display() {
    rectMode(CENTER);
    fill(c);
    rect(xpos, ypos, 20, 10);
  }

  void drive() {
    xpos = xpos + xspeed;
    if (xpos > width) {
      xpos = 0;
    }
  }
} //take note of the class's closing curly bracket

 

Print this page

Leave a Reply

Your email address will not be published. Required fields are marked *