Getter and setter methods

Figure 242. Direct access vs. setter method Slide presentation Create comment in forum
package hour_second.direct;

public class Time {
    public int hour, minute;
}
package hour_second;
import hour_second.direct.Time;

public class DirectAccess {
    Time time = new Time();
    void init() {
        time.hour = 17;
        time.minute = 45;
    }
}
package hour_second.setter;

public class Time {
    private int hour, minute;
    public void setTime(int h, int m) {
        minute = m;
        hour = h;
    }
}
package hour_second;
import hour_second.setter.Time;
public class SetterAccess {
    Time time = new Time();
    void init() { time.setTime(17, 45);}
}

Figure 243. Why adding setter methods? Slide presentation Create comment in forum
  • Allow for change of implementation.

  • Allow for non-business logic concerns. Examples:

    • Logging

    • Adding persistence


Figure 244. Implementation by minutes only Slide presentation Create comment in forum
package only_minute.direct;
public class Time {
  // Minutes since 00:00
  public int minute;
}
package only_minute;
import only_minute.direct.Time;
public class DirectAccess {
  Time time = new Time();
  void init() {
    time.minute = 1065;// 17:45
  }
}
package only_minute.setter;
public class Time {
  private int minute;
  public void setTime(int h, int m) {
    minute = m + 60 * h;
  }
}
package only_minute;
import only_minute.setter.Time;
public class SetterAccess {
    Time time = new Time();
    void init() { time.setTime(0, 0);}
}