Class 4
Functions
Functions - we know them
Functions - using
Functions - declaring
return type name (arguments) {our code}��• return type - The result of our function void, int, float, char (void means nothing returned)��• name - same as variables , no funny stuff.��• arguments - parameters for our function��• {our code} what we want to happen when it is called
Functions - declaring
Functions - declaring
Functions - declaring
Functions - scope of variables
�int i=5;
void setup(){� println(i);
}��result - prints 5
Functions - scope of variables
void setup(){
int i=5;
}�� void draw(){
println(i);
} �
result -Processing will not compile and say i is unknown
Functions - scope of variables
� void draw(){
int i=0;
i=i+1;
println(i);
} �
result - repeatedly printing “1”
Objects
objects
Objects
Objects
�Let’s assume someone has created an object called “ball” that knows how to move and bounce:
Objects - declaring
�Objects are declared the same, but we put the object’s (class) name as the type:�� Ball myBall;
Objects - initializing
variable name = new class name(parameters)
So, for our ball example, we probably have to set the initial location of the ball:
myBall = new Ball(100,100);
Objects - using
variable name . function name ( parameters);
myBall.changeColor(255,0,0);
Objects creating/defining classes
Objects - defining classes
Objects - class name
Remember? Ball myBall;�
• The syntax for naming your class is :
class name { class definition statements }
( No parentheses and no “void” )
Objects - data
class Ball {
int xPosition;� int yPosition:
…
…� }�
If you want to access these variables from another part of your code you can use the dot “.” notation i.e. myBall.xPosition
Objects - constructor
class Ball {
int xPosition;� int yPosition:
Ball(int _xPosition, int _yPosition ){� xPosition = _xPosition;
yPosition = _yPosition;� }
…
}
You can pass arguments like any function and they will be passed by “new”
Objects - functions
class Ball {
int xPosition;� int yPosition:
Ball(int _xPosition, int _yPosition ){� xPosition = _xPosition;
yPosition = _yPosition;� }
void changeColor(int newColor){
fill(newColor);
}
}
You can pass parameters like a regular function and the syntax to call this function would be :
ourBall.changeColor(255);