Reputation: 225
The Argument given is to prevent access from outsiders? Who are the outsiders?
and, does it benefits an individual programmer not part of any team? eg. like accidentally modifying program state.
Upvotes: 3
Views: 90
Reputation: 93
From my understanding, because I'm still a student. The private access will basically block the client from directly changing the instance variables in a class. You can search up what client means in java, but the definition of a client: is an entity that requests a service from another entity (ex: from class to a class) without being worried about how it got that service from the entity.
Upvotes: 0
Reputation: 91
Here is an example to help you understand
suppose you want to make a game in which you have a class Player which has health and you want to add or reduce health depending on what the player does
something like this:
class Player {
public String name;
public int health = 100;
public void addHealth(int amount) {
if(health + amount <= 100){
health = health + amount;
}else {
System.out.println("Invalid amount");
}
}
public void reduceHealth(int amount) {
if(health - amount >= 0){
health = health - amount;
}else {
System.out.println("Invalid amount");
}
}
}
now, if you keep the health field as public then you can change the health anytime you want by doing something like this
class main {
public static void main(String[] args) {
Player pl1 = new Player();
pl1.health = 50;
}
}
this is because you have set health to public but if you set health to private then you cannot directly change it.
you will have to call some public methods like addHealth() or reduceHealth() to change the value of health. this is also beneficial because you can add verification in those methods say, to make sure that health does not exceed 100 or go below 0.
but if you make health public then you may end up changing it to a wrong value by mistake and then your game will have bugs.
You will realize the importance of encapsulation in time
Upvotes: 1