Practical Coding in Java

Learn to write and validate your own code

Darren Kessner, PhD

(revised January 9, 2026)

Previous: HelloProcessing

Bounce

//
// Ball.java
//


//
// Notes:
//
// 1) In order to write your own class that uses PApplet functions,
// you must give objects of your class a PApplet reference.  Your
// object will store this reference as a private PApplet member
// variable.
//
// 2) Pass the PApplet reference to the constructor in order to
// initialize the member variable.
//
// 3) Use this reference to call any PApplet functions.
//


import processing.core.*;


public class Ball
{
    public Ball(PApplet p) // 2
    {
        this.p = p; // 2
        position = new PVector(200, 200);
        velocity = new PVector(p.random(-3, 3), p.random(-3, 3));
        radius = p.random(5, 20);
        c = p.color(p.random(256), p.random(256), p.random(256));
    }

    public void display()
    {
        p.fill(c); // 3: call PApplet functions via reference p
        p.ellipse(position.x, position.y, radius*2, radius*2);

        position.add(velocity);

        if (position.x < radius || position.x > p.width-radius)
            velocity.x *= -1;

        if (position.y < radius || position.y > p.height-radius)
            velocity.y *= -1;
    }

    private PApplet p; // 1: reference to main PApplet
    private PVector position;
    private PVector velocity;
    private float radius;
    private int c; // color
}

//
// Bounce.java
//


//
// Notes:
//
// 1) All of the actual Processing drawing code for each Ball is in
// the display() function of the Ball class above.
//
// 2) When you construct a new Ball, you must pass a reference to
// the PApplet class.  In the main program, Bounce extends PApplet
// (i.e. Bounce "is a" PApplet).  Inside a Bounce object, "this"
// refers to ourself.  In other words, "this" is the PApplet
// reference that we want to pass to our Ball objects.
//



import processing.core.*;
import java.util.*;   // for ArrayList


public class Bounce extends PApplet
{
    public void settings()
    {
        size(400, 400);
    }

    public void setup()
    {
        balls = new ArrayList<Ball>();
        balls.add(new Ball(this)); // 2: PApplet reference "this"
    }

    public void draw()
    {
        background(0);
        for (Ball b : balls)
            b.display(); // 1: draw the ball
    }

    public void keyPressed()
    {
        balls.add(new Ball(this)); // 2: PApplet reference "this"
    }

    private ArrayList<Ball> balls;

    public static void main(String[] args)
    {
        PApplet.main("Bounce");
    }
}

Next: