Step 2

Designing our Attack class


Before we start coding the “Attack” class, let’s think about how we want to design it. This is something all programmers do when creating classes, they come up with a design of what it should do before they actually program it.

Think of some things an “Attack” class should have, here we will make two, “damage” and “name.” Damage will be how much damage the attack does, name is going to be what the name of the attack is. There can defintely be more information about an attack, but let’s just stick with these two for now.

Go ahead and code these as shown. We also see a new accessor modifier called protected. The protected keyword means that only classes that are directly related to this class have access to this data, we will see how this is used more later.

Creating the Attack constructor


Next, lets add the shown code to create the constructor for our “Attack” class.

Notice how the constructor has parameters. This works just like with a function. Sometimes the constructor needs additional data to do its job. Here, we need to know the name and damage of the “Attack” before we create it.

We also see the keyword this. We need to use this because our parameters have the same name as our class variables. By using this we are saying to use the variable that belongs to the class, and not the one from the parameter.

With this code, we are setting our class variables to be the values of whatever was given to us from the parameters. Now whenever we create a new “Attack” it will already have its name and damage saved.

Creating the Attack getter functions


Next, lets add the shown code to create two getter functions in the “Attack” class.

A getter function is a small function whose only purpose is to help other classes get data. Right now our “damage” and “name” variables are protected, meaning most other classes don’t have access to this data. However, we still want other classes to be able to view this data without being able to modify it. To do this, we create these two functions to “get” this data so it can be viewed. However, because the variables are protected, other classes can only view it, they can’t ever change the data.

Awesome! This is actually all we need from our “Attack” class for now. Let’s move on to coding the “Fighter” next.