Practical Coding in Java

Learn to write and validate your own code

Darren Kessner, PhD

(revised October 21, 2025)

Previous: HelloProcessing

Ball

//
// 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
}


Next: