The reason why this is done is due to object orientation and encapsulation.
Lets take a car for example, (I'ma code in java, it's relatively similar, you'll hopefully get the idea).
The whole idea with encapsulation is that you don't need to understand everything the car contains, just as long as you've been given access to the methods you require to be able to successfully use it.
public class Car {
private final double FUEL_CAPACITY = 55;
private final double MAX_SPEED = 220;
private double fuel = 0;
private double speed = 0;
private boolean engineStarted = false;
public double getFuelLevel() {
return this.fuel;
}
public void addFuel(double amount) {
if (amount >= this.FUEL_CAPACITY)
return;
if (this.engineStarted == true)
return;
this.fuel += amount;
}
public void startEngine() {
// Don't start the car without fuel, don't want to break it.
if (this.fuel <= 0)
return;
this.engineStarted = true;
}
public void stopEngine() {
this.engineStarted = false;
while (this.speed >= 0)
decelerate(5);
// value of 5 is for example, normally you would calculate
// vehicle weight, road friction, down force, etc.
}
public void accelerate(double kph) {
if (this.engineStarted == false)
return;
if (this.speed + kph >= this.MAX_SPEED) {
this.speed = this.MAX_SPEED;
} else {
this.speed += kph;
}
}
public void decelerate(double kph) {
if (this.speed - kph <= 0) {
this.speed = 0;
} else {
this.speed -= kph;
}
}
public void drive() {
if (this.engineStarted == false)
return;
// example test run, drive to max speed then turn off the engine
while (this.speed <= this.MAX_SPEED) {
accelerate(10);
// do some stuff to calculate fuel consumption
}
this.stopEngine();
}
}
So as you can see, by removing direct access to the data members, and replacing the access with methods, you can more strictly control the conditions of access to the variables and also add in specified conditions.
Lets say that we had all of those data variables as public. Someone could create an instance of the car and say that the engine had more fuel than the actual tank can hold. In real world examples this can't happen, so you have to make sure it can't happen in the programming / virtual world as well. So to avoid programming bugs, errors and to more accurately imitate real world situations, we use getters, setters, methods and a combination of public / private variables.
I hope that cleared up a few things.