Can the get and set methods be used on any variables? I know it has to do with data encapsulation, but it doesn't really 'click' for me. What's the advantage gained by using them? Take the following code for example:
public class Bicycle {
private int cadence;
private int gear;
private int speed;
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
public int getCadence() {
return cadence;
}
public void setCadence(int newValue) {
cadence = newValue;
}
public int getGear() {
return gear;
}
public void setGear(int newValue) {
gear = newValue;
}
public int getSpeed() {
return speed;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
}
If I'm not mistaken, the cadence, gear and speed are private member variables. I assume this is so that other classes can't 'use' them. If that's the case, why does the code go on to make them public via get and set methods? Why not just make them public in the first place?