You prevent direct instance-variable
access by marking instance variables with the private
keyword.
You can, for example, redefine the Attraction
class as follows, with
minutes
marked with the
private
keyword, rather than with the
public
keyword:
public class Attraction { // First, define instance variable: private int minutes; // Define zero-parameter constructor: public Attraction () {minutes = 75;} // Define one-parameter constructor: public Attraction (int m) {minutes = m;} // Define getter: public int getMinutes () {return minutes;} // Define setter: public void setMinutes (int m) {minutes = m;} }
With the Attraction
class so redefined, attempts to access an
attraction's instance-variable values from outside the Attraction
class fail to compile:
x.minutes <-- Access fails to compile; the minutes instance variable is private x.minutes = 6 <-- Assignment fails to compile; the minutes instance variable is private