The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


A common motivation for creating a new Object type is to take several related pieces of data and encapsulate them into an object that can be manipulated (passed as an argument, operated on) as a single unit. We have already seen two built-in types like this, Point and Rectangle.

Another example, which we will implement ourselves, is Time, which is used to record the time of day. The various pieces of information that form a time are the hour, minute and second. Because every Time object will contain these data, we need to create instance variables to hold them.

The first step is to decide what type each variable should be. It seems clear that hour and minute should be integers. Just to keep things interesting, let's make second a double, so we can record fractions of a second.

Instance variables are declared at the beginning of the class definition, outside of any method definition, like this:

class Time {
  int hour, minute;
  double second;

All by itself, this code fragment is a legal class definition. The state diagram for a Time object would look like this:

After declaring the instance variables, the next step is usually to define a constructor for the new class.

Last Update: 2011-01-24