- Learning Java by Building Android Games
- John Horton
- 210字
- 2021-07-23 19:02:31
Class implementation
Here is real code for our hypothetical class for our hypothetical game. We call it a class implementation. As the class is called Soldier
, if we implement this for real we would do so in a file called Soldier.java
.
public class Soldier { // Member variables int health; String soldierType; // Method of the class void shootEnemy(){ // bang bang } }
Above is an implementation for a class called Soldier
. There are two, member variables or fields, an int
variable called health
and a String
variable called soldierType
.
There is also a method called shootEnemy
. The method has no parameters and a void
return type, but class methods can be of any shape or size that we discussed in Chapter 4, Structuring Code with Java Methods.
To be precise about member variables and fields, when the class is instantiated into a real object the fields become variables of the object itself and we call them instance or member variables.
They are just variables of the class whichever fancy name they are referred to by. Although the difference between fields and variables declared in methods (called local variables) does become more important as we progress. We will look at all types of variables again later in this chapter.