Once you have identified the instance variables for your class the next thing to consider is the constructor. In Java, constructors have the same name as the class and are declared public. They are declared without a return type. So any method that is named the same as the class and has no return type is a constructor. Our constructor will take two parameters: the numerator and the denominator. Listingย 6.3.1 shows the constructor for the Fraction class.
There are a couple of important things to notice here. First, you will notice that the constructor does not have a self parameter. You will also notice that we can simply refer to the instance variables by name without the self prefix, because they have already been declared. This allows the Java compiler to do the work of dereferencing the current Java object. Java does provide a special variable called this that works like the self variable. In Java, this is typically only used when it is needed to differentiate between a parameter or local variable and an instance variable. For example,Listingย 6.3.1 shows an alternate definition of the the Fraction constructor that uses this to differentiate between parameters and instance variables.
Rearrange the blocks to create a Player class with a private int health instance variable. Implement a getter and a setter that validates health points to remain within 0 and 100.
public class Player {
private int health;
---
public class Player {
public int health;
#paired
---
public int getHealth() {
return health;
}
---
public void getHealth() {
return health;
}
#paired
---
public void setHealth(int health) {
if (health >= 0 && health <= 100) {
this.health = health;
}
}
---
public void setHealth(int health) {
if (health >= 0 && health <= 100) {
health = health;
}
}
#paired
---
}