Home Segments Top Top Previous Next

285: Mainline

If you like, you can combine the virtues of private and protected placement. First, you return the minutes instance variables to the private part of the Attraction class definition, to prevent accidental writing by instance methods defined outside the Attraction class. Second, you provide access to the minutes instance variable's value through a getter and setter defined in the protected part of the Attraction class definition:

public class Attraction {
 // Define zero-parameter constructor:
 public Attraction () {minutes = 75;}
 // Define one-parameter constructor:
 public Attraction (int m) {minutes = m;}
 // Define protected methods:
 // Define getter:
 protected int getMinutes () {return minutes;}          
 // Define setter:
 protected void setMinutes (int m) {minutes = m;}       
 // Define private variable:
 private int minutes;                                   
} 

Because the instance variable is in the private part of the Attraction class definition, it is accessible to only those instance methods that are defined in the Attraction class. Because the getter and setter are in the protected part of the Attraction class definition, they are also accessible to instance methods defined in subclasses of the Attraction class.