In object-oriented programming (OOP), encapsulation refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object’s components.
Why we are using Encapsulation?
- You are able to protect the members of a class from external access in order to really guard against unauthorized access.
With Encapsulation
package anote;
class Player {
private String name;
private int health = 100;
private String weapon;
public Player(String name, int health, String weapon) {
this.name = name;
if (health > 0 && health <= 100) {
this.health = health;
}
this.weapon = weapon;
}
public void loseHealth(int damage) {
this.health = this.health - damage;
if (this.health <= 0) {
System.out.println("Player knocked out");
}
}
public int getHealth() {
return health;
}
}
public class Main {
public static void main(String[] args) {
Player player = new Player("Tim", 200, "Sword");
System.out.println("Initial health is " + player.getHealth());
}
}
Initial health is 100
Without Encapsulation
The problem without Encapsulation
- We have got the ability to change the player’s fields directly.
package anote;
class Player {
public String name;
public int health;
public String weapon;
public void loseHealth(int damage) {
this.health = this.health - damage;
if (this.health <= 0) {
System.out.println("Player knocked out");
}
}
public int healthRemaining() {
return this.health;
}
}
public class Main {
public static void main(String[] args) {
Player player = new Player();
player.name = "Tim";
player.health = 20;
player.weapon = "Sword";
int damage = 10;
player.loseHealth(damage);
System.out.println("Remaining health = " + player.healthRemaining());
damage = 11;
player.loseHealth(damage);
System.out.println("Remaining health = " + player.healthRemaining());
}
}
Remaining health = 10
Player knocked out
Remaining health = -1