0

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?

Aaron Ausmus
  • 53
  • 1
  • 1
  • 6
  • 1
    It's a good question but, you're [not the first](http://stackoverflow.com/a/1568230/645270) to ask this. – keyser Dec 11 '13 at 00:04
  • I read that thread, but the answers provided are above my pay grade so to speak. Is there a more simple answer? I'm not as experienced as the programmers on that thread. – Aaron Ausmus Dec 11 '13 at 00:10

0 Answers0