Home Segments Top Top Previous Next

223: Mainline

A getter is a method that extracts information from an instance.

One reason that you may wish to use a getter, rather than accessing an instance variable directly, is that you can include additional computation in a getter. For example, if you are concerned about how often your program accesses the minutes instance variable, you can add a statement to the getMinutes getter that announces each access:

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