Step 4

Creating the Ball class variables

Next, let’s start coding the “Ball” class. Open up the “Ball” file and add the code as shown here.

For this “Ball” class, we’re going to pretty much use the same class variables as the last project. (If you need a refresher on any of these, feel free to go back to that project and take a look.)

The main differences here are with the last two class variables. The “canvas” variable is a reference to the “CanvasPanel” so we can communicate with it. “Ellipse2D” will be used to draw the circle, its a little more advanced than how we drew before, but it will be needed for this project.

Also notice on the top that we have the keyword implements. This means that this class is trying to be a part of an interface, here it is the “Sprite” interface. Right now there is an error because it hasn’t completed the requirements/rules of the “Sprite” interface yet, we’ll fix this soon.

Creating the Ball constructor

Next, add the code as shown here to complete the “Ball” constructor.

Here we setup the x, y, and canvas, variables to be what was given by the parameters. We also create our “Ellipse2D” using the parameters, it works very similar to before, you give it an x and y and a height and width.

Lastly, we tell this canvas to add this sprite to it with the “addSprite” function. We haven’t made this function yet but we will soon.

Satisfying the Sprite requirements

Next, add the code as shown here to satisfy the requirements for “Ball” to implement the “Sprite” interface.

We’re going to code this more later on, but for now we’re mainly just trying to satisfy the requirements of “Sprite” so we can get rid of all the errors in this file.

Don’t forget to use the “@Override”, this is what tells Java these functions are used to satisfy the requirements of implementing an interface.

Before we move on, double check your code from this section for any errors. There’s going to be a lot more setup for this project before we can test anything out, so the more you keep an eye out for errors the better. Once we’ve finished our main setup, we’ll be able to test a lot more.