-
Notifications
You must be signed in to change notification settings - Fork 0
/
EnhancedPlayer.java
34 lines (28 loc) · 1008 Bytes
/
EnhancedPlayer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class EnhancedPlayer {
// In this class, we will apply ENCAPSULATION unlike the 'Player' class.
// So we are declaring fields as 'private'.
private String name;
private int health = 100;
private String weapon;
public EnhancedPlayer(String name, int health, String weapon) {
this.name = name;
// Validation
if (health > 0 && health <= 100) {
this.health = health;
}
this.weapon = weapon;
}
public void loseHealth(int damage) {
this.health -= damage;
if (this.health <= 0) {
System.out.println("Player knocked out");
}
// Reduce no. of lives of player.
}
public int getHealth() {
return health;
}
// Another advantage of encapsulation is that if we change any of the field name
// in this class then we don't need to change it in another class as no other
// class is accessing it(we are accessing it using getter from another class).
}