8

Objects

No object is so beautiful that, under certain conditions, it will not look ugly.

—Oscar Wilde

In this chapter:

 Data and functionality, together at last

 What is an object?

 What is a class?

 Writing your own classes

 Creating your own objects

 Processing tabs

8-1 I’m down with OOP

Before I begin discussing the details of how object-oriented programming (OOP) works in Processing, let’s embark on a short conceptual discussion of “objects” themselves. It’s important to understand that I am not introducing any new programming fundamentals. Objects use everything you have already learned: variables, conditional statements, loops, functions, and so on. What is entirely new, however, is a way of thinking, a way of structuring and organizing everything you have already learned.

Imagine you were not programming in Processing, but were instead writing out a program for your day, a list of instructions, if you will. It might start out something like:

 Wake up.

 Drink coffee (or tea).

 Eat breakfast: cereal, blueberries, and soy milk.

 Ride the subway.

What is involved here? Specifically, what things are involved? First, although it may not be immediately apparent from how I wrote the above instructions, the main thing is you, a human being, a person. You exhibit certain properties. You look a certain way; perhaps you have brown hair, wear glasses, and appear slightly nerdy. You also have the ability to do stuff, such as wake up (presumably you can also sleep), eat, or ride the subway. An object is just like you, a thing that has properties and can do stuff.

So how does this relate to programming? The properties of an object are variables; and the stuff an object can do are functions. Object-oriented programming is the marriage of everything I covered in Chapter 1 through Chapter 7; data and functionality, all rolled into one thing.

Let’s map out the data and functions for a very simple human object:

Human data

 Height.

 Weight.

 Gender.

 Eye color.

 Hair color.

Human functions

 Sleep.

 Wake up.

 Eat.

 Ride some form of transportation.

Now, before I get too much further, I need to embark on a brief metaphysical digression. The above structure is not a human being itself; it simply describes the idea, or the concept, behind a human being. It describes what it is to be human. To be human is to have height, hair, to sleep, to eat, and so on. This is a crucial distinction for programming objects. This human being template is known as a class. A class is different from an object. You are an object. I am an object. That guy on the subway is an object. Albert Einstein is an object. We are all people, real world instances of the idea of a human being.

Think of a cookie cutter. A cookie cutter makes cookies, but it is not a cookie itself. The cookie cutter is the class, the cookies are the objects.

Exercise 8-1

Consider a car as an object. What data would a car have? What functions would it have?

in08-01-9780123944436

Car dataCar functions
______________________________________________________
______________________________________________________
______________________________________________________
______________________________________________________
______________________________________________________

8-2 Using an object

Before I look at the actual writing of a class itself, let’s briefly look at how using objects in the main program (i.e., setup() and draw()) makes the world a better place.

Returning to the car example from Chapter 7, you may recall that the pseudocode for the sketch looked something like this:

Data (Global Variables):

 Car color.

 Car x location.

 Car y location.

 Car x speed.

Setup:

 Initialize car color.

 Initialize car location to starting point.

 Initialize car speed.

Draw:

 Fill background.

 Display car at location with color.

 Increment car’s location by speed.

In Chapter 7, I defined global variables at the top of the program, initialized them in setup(), and called functions to move and display the car in draw().

Object-oriented programming allows me to take all of the variables and functions out of the main program and store them inside a car object. A car object will know about its data — color, location, speed. That is part one. Part two of the car object is the stuff it can do, the methods (functions inside an object). The car can move and it can be displayed.

Using object-oriented design, the pseudocode improves to look something like this:

Data (Global Variables):

 Car object.

Setup:

 Initialize car object.

Draw:

 Fill background.

 Display car object.

 Move car object.

Notice I removed all of the global variables from the first example. Instead of having separate variables for car color, car location, and car speed, I now have only one variable, a Car variable! And instead of initializing those three variables, I initialize one thing, the Car object. Where did those variables go? They still exist, only now they live inside of the Car object (and will be defined in the Car class, which I will get to in a moment).

Moving beyond pseudocode, the actual body of the sketch might look like:

u08-01-9780123944436

I am going to get into the details regarding the previous code in a moment, but before I do so, let’s take a look at how the Car class itself is written.

8-3 Writing the cookie cutter

The simple car example above demonstrates how the use of object in Processing makes for clean, readable code. The hard work goes into writing the object template, that is the class itself. When you’re first learning about object-oriented programming, it’s often a useful exercise to take a program written without objects and, not changing the functionality at all, rewrite it using objects. I will do exactly this with the car example from Chapter 7, recreating exactly the same look and behavior in an object-oriented manner. And at the end of the chapter, I will remake Zoog as an object.

All classes must include four elements: name, data, constructor, and methods. (Technically, the only actual required element is the class name, but the point of doing object-oriented programming is to include all of these.)

Figure 8-1 shows how you can take the elements from a simple non-object-oriented sketch and place them into a Car class, from which you will then be able to make Car objects.

f08-01-9780123944436

Figure 8-1

 The Class Name — The name is specified by “class WhateverNameYouChoose”. You then enclose all of the code for the class inside curly brackets after the name declaration. Class names are traditionally capitalized (to distinguish them from variable names, which traditionally are lowercase).

 Data — The data for a class is a collection of variables. These variables are often referred to as instance variables since each instance of an object contains this set of variables.

 A Constructor — The constructor is a special function inside of a class that creates the instance of the object itself. It’s where you give the instructions on how to set up the object. It’s just like Processing’s setup() function, only here it’s used to create an individual object within the sketch, whenever a new object is created from this class. It always has the same name as the class and is called by invoking the new operator: “Car myCar = new Car();”.

 Functionality — We can add functionality to an object by writing methods. These are done in the same way as described in Chapter 7, with a return type, name, arguments, and a body of code.

This code for a class exists as its own block and can be placed anywhere outside of setup() and draw().

A class is a new block of code!

void setup() {

}

void draw() {

}

class Car {

}

Exercise 8-2

Fill in the blanks in the following Human class definition. Include a function called sleep() or make up your own function. Follow the syntax of the Car example. (There are no right or wrong answers in terms of the actual code itself; it’s the structure that is important.)

in08-01-9780123944436

________ ______________ {

 color hairColor;

 float height;

 _______________________________ {

  _____________________________________

  _____________________________________

 }

 _______________________________ {

  _____________________________________

  _____________________________________

 }

}

8-4 Using an object: the details

In Section 8-2 on page 141, I took a quick peek at how an object can greatly simplify the main parts of a Processing sketch (setup() and draw()).

u08-02-9780123944436

Let’s look at the details behind the above three steps outlining how to use an object in your sketch.

Step 1. Declaring an object variable.
If you flip back to Chapter 4, you may recall that a variable is declared by specifying a type and a name.
// Variable declaration
// type name
int var;
The above is an example of a variable that holds onto a primitive, in this case an integer. As you learned in Chapter 4, primitive data types are singular pieces of information: an integer, a floating point number, a character. Declaring a variable that holds onto an object is quite similar. The difference is that here the type is the class name, something I will make up, in this case Car. Objects, incidentally, are not primitives and are considered complex data types. (This is because they store multiple pieces of information: data and functionality. Primitives only store data.)

Step 2. Initializing an object.
Again, you may recall from Chapter 4 that in order to initialize a variable (i.e., give it a starting value), I use an assignment operation — variable equals something.
// Variable Initialization
// var equals 10
var = 10;
Initializing an object is a bit more complex. Instead of simply assigning it a primitive value, like an integer or floating point number, you have to construct the object. An object is made with the new operator.

u08-03-9780123944436

In the above example, myCar is the object variable name and "=" indicates you are setting it equal to something, that something being a new instance of a Car object. What I am really doing here is initializing a Car object. When you initialize a primitive variable, such as an integer, you just set it equal to a number. But an object may contain multiple pieces of data. Recalling the Car class from the previous section, you can see that this line of code calls the constructor, a special function named Car() that initializes all of the object’s variables and makes sure the Car object is ready to go.
One other thing; with the primitive integer var, if you had forgotten to initialize it (set it equal to 10), Processing would have assigned it a default value, zero. An object variable (such as myCar), however, has no default value. If you forget to initialize an object, Processing will give it the value null. null means nothing. Not zero. Not negative one. Utter nothingness. Emptiness. If you encounter an error in the message window that says NullPointerException (and this is a pretty common error), that error is most likely caused by having forgotten to initialize an object. (See the Appendix for more details.)

Step 3. Using an object
Once you have successfully declared and initialized an object variable, you can use it. Using an object involves calling functions that are built into that object. A human object can eat, a car can drive, a dog can bark. Functions that are inside of an object are technically referred to as “methods” in Java so I can begin to use this nomenclature (see Section 7-1 on page 117). Calling a method inside of an object is accomplished via dot syntax:
variableName.objectMethod(method arguments);
In the case of the car, none of the available functions has an argument so it looks like:

u08-04-9780123944436

Exercise 8-3

Assume the existence of a Human class. You want to write the code to declare a Human object as well as call the function sleep() on that human object. Write out the code below:

in08-01-9780123944436

Declare and initialize the Human object: __________________________

Call the sleep() function: __________________________

8-5 Putting it together with a tab

Now that I have covered how to define a class and use an object born from that class, I can take the code from Section 8-2 on page 141 and Section 8-3 on page 143 and put them together in one sketch.

Example 8-1

A Car class and a Car object

u08-05-9780123944436

You will notice that the code block that contains the Car class is placed below the main body of the program (under draw()). This spot is identical to where I placed user-defined functions in Chapter 7. Technically speaking, the order does not matter, as long as the blocks of code (contained within curly brackets) remain intact. The Car class could go above setup() or it could even go between setup() and draw(). Though any placement is technically correct, when programming, it’s nice to place things where they make the most logical sense to our human brains, the bottom of the code being a good starting point. Nevertheless, Processing offers a useful means for separating blocks of code from each other through the use of tabs.

In your Processing window, look for the upside-down triangle next to the name of your sketch. If you click that triangle, you will see that it offers the “New Tab” option shown in Figure 8-2.

f08-02-9780123944436

Figure 8-2

Upon selecting “New Tab,” you will be prompted to type in a name for the new tab, as shown in Figure 8-3.

f08-03-9780123944436

Figure 8-3

Although you can pick any name you like, it’s probably a good idea to name the tab after the class you intend to put there. You can then put your main code (setup() and draw()) on the original tab (named “ObjectExample” in Figure 8-4) and type the code for your class in the new one (named “Car”).

f08-04-9780123944436

Figure 8-4

Toggling between the tabs is simple, just click on the tab name itself. Also, it should be noted that when a new tab is created, a new .pde file is created inside the sketch folder, as shown in Figure 8-5. The program has both an ObjectExample.pde file and Car.pde file.

f08-05-9780123944436

Figure 8-5

in08-01-9780123944436Exercise 8-4: Create a sketch with multiple tabs. Try to get the Car example to run without any errors.

8-6 Constructor arguments

In the previous examples, the car object was initialized using the new operator followed by the constructor for the class.

Car myCar = new Car();

This was a useful simplification while you learned the basics of OOP. Nonetheless, there is a rather serious problem with the above code. What if I wanted to write a program with two car objects?

u08-06-9780123944436

This accomplishes my goal; the code will produce two car objects, one stored in the variable myCar1 and one in myCar2. However, if you study the Car class, you will notice that these two cars will be identical: each one will be colored white, start in the middle of the screen, and have a speed of 1. In English, the above reads:

Make a new car.

I want to instead say:

Make a new red car, at location (0,10) with a speed of 1.

So that I could also say:

Make a new blue car, at location (0,100) with a speed of 2.

I can do this by placing arguments inside of the constructor.

Car myCar = new Car(color(255, 0, 0), 0, 100, 2);

The constructor must be rewritten to incorporate these arguments:

Car(color tempC, float tempXpos, float tempYpos, float tempXspeed) {

 c = tempC;

 xpos = tempXpos;

 ypos = tempYpos;

 xspeed = tempXspeed;

}

In my experience, the use of constructor arguments to initialize object variables can be somewhat bewildering. Please don’t blame yourself. The code is strange-looking and can seem awfully redundant: “For every single variable I want to initialize in the constructor, I have to duplicate it with a temporary argument to that constructor?”

Nevertheless, this is quite an important skill to learn, and, ultimately, is one of the things that makes object-oriented programming powerful. But for now, it may feel painful. Let’s briefly revisit parameter passing again to understand how it works in this context. See Figure 8-6.

f08-06-9780123944436

Figure 8-6

Arguments are local variables used inside the body of a function that get filled with values when the function is called. In the examples, they have one purpose only, to initialize the variables inside of an object. These are the variables that count, the car’s actual color, the car’s actual x location, and so on. The constructor’s arguments are just temporary, and exist solely to pass a value from where the object is made into the object itself.

This allows you to make a variety of objects using the same constructor. You might also just write the word temp in your argument names to remind you of what is going on (x vs. tempX). You will also see programmers use an underscore (x vs. x_) in many examples. I’ll probably do it this way in some examples towards the end of this book. You can name these whatever you want, of course. However, it’s advisable to choose a name that makes sense to you, and also to stay consistent.

I can now write the same program with multiple object instances, each with unique properties.

u08-07-9780123944436

Figure 8-7

Example 8-2

Two Car objects

u08-08-9780123944436

Exercise 8-5

Rewrite the gravity example from Chapter 5 using objects with a Ball class. The original example is included here for your reference with a framework to help you get started. Once you get one object working, make two without changing the class! Can you add variables for color or size in your class?

in08-01-9780123944436

u08-09-9780123944436

8-7 Objects are data types too!

This is your first experience with object-oriented programming, so I want to take it easy. The examples in this chapter all use just one class and make, at most, two or three objects from that class. Nevertheless, there are no actual limitations. A Processing sketch can include as many classes as you feel like writing. If you were programming the Space Invaders game, for example, you might create a Spaceship class, an Enemy class, and a Bullet class, using an object for each entity in your game.

In addition, although not primitive, classes are data types just like integers and floats. And since classes are made up of data, an object can therefore contain other objects! For example, let’s assume you had just finished programming a Fork and Spoon class. Moving on to a PlaceSetting class, you would likely include variables for both a Fork object and a Spoon object inside that class itself. This is perfectly reasonable and quite common in object-oriented programming.

u08-10-9780123944436

Objects, just like any data type, can also be passed in as arguments to a function. In the Space Invaders game example, if the spaceship shoots the bullet at the enemy, you would probably want to write a function inside the Enemy class to determine if the enemy had been hit by the bullet.

u08-11-9780123944436

In Chapter 7, I showed how when a primitive value (int, float, etc.) is passed into a function, a copy of the variable is made and the original variable remains the same no matter what happens in the function. This is known as pass by value. With objects, things work a bit differently. If changes are made to an object after it is passed into a function, those changes will affect the original object. Instead of copying the object and passing it into the function, a copy of a reference to the object is passed. You can think of a reference as the address in memory where the object’s data is stored. So while there are in fact two distinct variables holding on their own value, that value is simply an address pointing to only one object. Any changes to those object variables affect the same object.

u08-12-9780123944436

Figure 8-8

As you move forward through this book and the examples become more advanced, you will see examples that use multiple objects, pass objects into functions, and more. The next chapter, in fact, focuses on how to make lists of objects. And Chapter 10 walks through the development of a project that includes multiple classes. For now, as I close out the chapter with Zoog, I will stick with just one class.

8-8 Object-oriented Zoog

Invariably, the question comes up: “When should I use object-oriented programming?” For me, the answer is always. Objects allow you to organize the concepts inside of a software application into modular, reusable packages. You will see this again and again throughout the course of this book. However, it’s not always convenient or necessary to start out every project using object-orientation, especially while you’re learning. Processing makes it easy to quickly “sketch” out visual ideas with non object-oriented code.

For any Processing project you want to make, my advice is to take a step-by-step approach. You do not need to start out writing classes for everything you want to try to do. Sketch out your idea first by writing code in setup() and draw(). Nail down the logic of what you want to do as well as how you want it to look. As your project begins to grow, take the time to reorganize your code, perhaps first with functions, then with objects. It’s perfectly acceptable to dedicate a significant chunk of your time to this reorganization process (often referred to as refactoring) without making any changes to the end result, that is, what your sketch looks like and does on screen.

This is exactly what I have been doing with cosmonaut Zoog from Chapter 1 until now. I sketched out Zoog’s look and experimented with some motion behaviors. Now that I have something, I can take the time to refactor by making Zoog into an object. This process will give you a leg up in programming Zoog’s future life in more complex sketches.

And so it is time to take the plunge and make a Zoog class. Our little Zoog is almost all grown up. The following example is virtually identical to Example 7-6 (Zoog with functions) with one major difference. All of the variables and all of the functions are now incorporated into the Zoog class with setup() and draw() containing barely any code.

u08-14-9780123944436

Figure 8-9

in08-01-9780123944436Exercise 8-6: Rewrite Example 8-3 to include two Zoogs. Can you vary their appearance? Behavior? Consider adding color as a Zoog variable.

Example 8-3

Zoog object

u08-13-9780123944436

Lesson Three Project

in08-01-9780123944436

1. Take your Lesson Two Project and reorganize the code using functions.

2. Reorganize the code one step further using a class and an object variable.

3. Add arguments to the Constructor of your class and try making two or three objects with different variables.

Use the space provided below to sketch designs, notes, and pseudocode for your project.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.202.54