An Introduction To Programming With Processing

Object Instantiation

Object instantiation is not a new concept to you as you have already instantiated objects from the PImage class. The process of instantiating an object from our Button class will follow a very similar pattern. Since we want this object to be accessible from both setup(), draw() and user defined functions we are going to declare an object variable in the global variable scope by adding the following declaration outside of both setup() and draw():
Button myButton;
We now have a variable name that we can use to reference the object we just instantiated from the Button class, this name is myButton. Within the setup() structure we'll initialize the button, by use of it's constructor:
myButton = new Button(color(255), width/2, height/2, 100, 40, "myButton");
myButton (the object variable) has inherited the properties of the Button class. If you were to compare this statement with the modified example of the class's constructor:
//this is simply for illustrative purposes
Button(cB, xLocB, yLocB, xSizeB, ySizeB, nameB);
You will notice that this button is currently being constructed, but remember that you will not actually see the button at this stage as all we have done is told Processing how we would like the button to be constructed we have not told Processing to actually display the button. The use of the new keyword in the previous listed assignment statement is followed by the class's constructor which is why we are using Button() and not Button. Now that we have told Processing how we would like this new button constructed let's move onto the draw() structure and actually render the button. Using an object's method is easy, and is very similar to a function call. The main difference is that the name of the method is preceded by the name of the object itself. For example:
Add this statement to the draw() structure, and you'll finally see your button.
Object Instantiation
As you can see when working with OOP the main program looks less cluttered with code and the majority of the code exists in creating classes. This for many people creates a more readable interface for designing software, and once you get the hang of using OOP it can also help to localize problematic code that might be difficult to locate without a program adopting a modular design. The completed sketch ButonClassExample.pde also contains another method called over() which will identify if the users mouse is over the button, if you take some time to examine the sketch you should be able to add your own functionality to the button.

Download the example file