Home Segments Top Top Previous Next

226: Mainline

One reason that you may wish to use a setter, rather than assigning a value to an instance variable directly, is that you can include additional computation in a setter. In Segment 223, you saw how to add a statement to the getMinutes getter that announces each access. The following provides the same enhancement to the setMinutes setter:

public class Attraction {
 public int minutes;
 public Attraction () {minutes = 75;}
 public Attraction (int m) {minutes = m;}
 // Define getter:
 public int getMinutes () {
  return minutes;
 }
 // Define setter:
 public void setMinutes (int m) {
  System.out.println("Assigning a value ...");   
  minutes = m; 
 } 
}