How to store data in Java objects

A timely introduction to using instance variables in your Java classes

1 2 Page 2
Page 2 of 2

Okay -- you're ready to manipulate the snooze interval. You do this by adding get and set methods for the snooze interval. When you have an instance variable like snoozeInterval, you will regularly call the get and set methods getSnoozeInterval() and setSnoozeInterval().

public class AlarmClock {
  long m_snoozeInterval = 5000;    // Snooze time in millisecond
  // Set method for m_snoozeInterval.
  public void setSnoozeInterval(long snoozeInterval) {
    m_snoozeInterval = snoozeInterval;
  }
  // Get method for m_snoozeInterval.
  // Note that you are returning a value of type long here.
  public long getSnoozeInterval() {
    // Here's the line that returns the value.
    return m_snoozeInterval;
  }
  public void snooze() {
    // You can still get to m_snoozeInterval in an AlarmClock method
    // because you are within the scope of the class.
    System.out.println("ZZZZZ for: " + m_snoozeInterval);
   }
}
public class AlarmClockTest {
  public static void main(String[] args) {
    // Create two clocks. Each has its own m_snoozeInterval.
    AlarmClock aClock1 = new AlarmClock();
    AlarmClock aClock2 = new AlarmClock();
    // Change aClock2. You use the set method.
    aClock2.setSnoozeInterval(10000);
    aClock1.snooze();    // Snooze with aClock1's interval.
    aClock2.snooze();    // Snooze with aClock2's interval.
  }
}

Defined now are two methods to manipulate the snooze interval. One is used to get the snooze interval, and the other is used to set it. That may seem trivial, but then, AlarmClock is a trivial class. 

Conclusion

In this quick tutorial you've looked at how to manipulate primitive types like int and double. You examined local variables, method parameters, and variable scope. You learned how to add data to classes using instance variables, and how that data is contained in each instance. Finally, you explored encapsulation and how it leads to better code.

Want to keep going? Learn more about using types, identifiers, and literals in your Java programs.

1 2 Page 2
Page 2 of 2