To begin our look at Object oriented programming, we'll look at the simple task of animating a ball moving across the Processing canvas.
First, we'll look at the code in the Ball Class Definition, then we'll look at the main tab code to see how to create an instance of a Ball Class object.
Below is a UML (Unified Modeling Language) Class diagram which gives an overview of the important information about the Ball class. In the top section is the class name, the second section shows the instance variables or properties of the class. The bottom section shows the class methods, which are functions that belong to the class. UML Class Diagram Specification
//Definition for Ball ClassclassBall{//instance variables or propertiesfloat x; float y;float size;//additional variables (these ones are not shown in UML Class Diagram)float speedX;float speedY; color ballColor;//////Class Constructors - to initialize instance variables/////Overloaded versions - each with a unique parameter listBall(){ //default constructor takes no input parametersthis( 5,5,50); //calls the Ball constructor Ball(5,5,50) }Ball(float _x,float y,float size ){ x = _x; //initialize instance variable: xthis.y= y; //initialize instance variable: ythis.size= size; speedX =5; //the same for every object speedY =10; //the same for every object ballColor =color( 100); //default ball color is gray }Ball(float _x,float y,float size,float speedX,float speedY, color ballColor ){ x = _x; //initialize instance variable: xthis.y= y;this.size= size;this.speedX= speedX; //the same for every objectthis.speedY= speedY; //the same for every objectthis.ballColor= ballColor; }////////////Methods or functions//displays the ballvoiddisplay(){fill( ballColor);ellipse( x, y, size, size); //diameter } //end display method//determines new position for ball each time this is executedvoidmove(){if( x > width || x <0){ speedX *=-1; }if( y > height || y <0){ speedY *=-1; } x += speedX; y += speedY; } // end move method} //end of class Ball////Main Tab Code:Ball ball1; //ball1 = null//declare a variable that can point to a ball object's data in heap memoryBall[] balls; //declare the array of Ball objectsvoidsetup() {size( 600,600);colorMode(HSB,360,100,100);///create 1 Ball object instance ball1 =newBall(20,20,30,15,5, color(255,0,0)); //new is the keyword used to create an object instanceballs =newBall[100]; //initialize the arrayfor ( int i=0; i<balls.length; i++) {float x =random(0, width);float y =random(0, height);float hue =random(0,360); balls[i] =newBall(x, y,20,5,10, color( hue,100,100)); //called the constructor - we have an object instance } //end of for}//end of setupvoiddraw() {background(255);//have each ball execute it's move methodball1.move();//have each ball display itselfball1.display();//use for-loop to move and display all ballsfor ( int i=0; i<balls.length; i++) { balls[i].move(); balls[i].display(); } //end for} //end draw