Class action

Discover more about creating Java classes

1 2 Page 2
Page 2 of 2
public class AlarmClockTest {
  public static void main(String[] args) {
    // Create one alarm clock set to go off at 6:15 (Ugh)
    AlarmClock ac1 = new AlarmClock(6,15);
    // Create another alarm clock without setting the alarm.
    AlarmClock ac2 = new AlarmClock();
    System.out.println("Alarm setting is " + ac1.getAlarmHour() + ":" +
                        ac1.getAlarmMinute());
    System.out.println("Alarm setting 2 is " + ac2.getAlarmHour() + ":" +
                        ac2.getAlarmMinute());
  }
}

Type in and compile the above code, and you'll see that it all works. If you run it, you'll find that the first alarm time is set to 6:15, and that the second alarm time is set to 00:00. Wait a minute ... who or what set the second alarm time?

The answer is that the instance variables in a class are always initialized, even if no constructor exists. The compiler automatically initializes them when it creates an instance. If you have an initial value specified (as we do with the snooze interval) the complier will use that for the initialization. If you don't have an initial value, it will use defaults as listed below.

  • Numerical values -- 0
  • Boolean values -- false
  • Object references -- null

We'll go into more detail on null and Boolean in a later column.

To review, the list below describes what happens when you create a new instance of a class:

  • Memory is allocated, and a new object of the specified type is created
  • The object's instance variables initialize
  • A constructor is called
  • After the constructor returns, you've got an object

Conclusion

In this column, we've considerably expanded the complexity and capability of our AlarmClock class. We've learned how to protect its integrity, and we've discovered some very important concepts about using constructors to initialize instances.

In our next column, our alarm clock will grow more secure as we learn how to ensure that any arguments passed in to our methods are valid. We'll also start adding some notion of actual time to the class. If you have some time of your own, take a look in the Java documentation at the Date and Calendar classes in Resources. See you next time!

Jacob Weintraub is founder and president of LearningPatterns.com (LPc). Jacob has been working in object technologies since 1989, and teaching Java since 1995. He authored LPc's Java for Programmers, as well as many of its advanced courses, such as those on OOAD and EJB.

Learn more about this topic

  • Previous Java 101 columns

1 2 Page 2
Page 2 of 2