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.

Class Definitions and Object Types

Every time you write a class definition, you create a new Object type, with the same name as the class. Way back in Section 1.5, when we defined the class named Hello, we also created an object type named Hello. We didn't create any variables with type Hello, and we didn't use the new command to create any Hello objects, but we could have!

That example may not make any sense, since there is no reason to create a Hello object, and it is not clear what it would be good for if we did. In this chapter, we will look at some examples of class definitions that create useful new Object types.

Here are the most important ideas in this chapter:

  • Defining a new class also creates a new object type with the same name.
  • A class definition is like a template for objects: it determines what instance variables the objects have and what methods can operate on them.
  • Every object belongs to some object type; hence, it is an instance of some class.
  • When you invoke the new command to create an object, Java invokes a special method called a constructor to initialize the instance variables. You provide one or more constructors as part of the class definition.
  • Typically all the methods that operate on a type go in the class definition for that type.

Here are some syntax issues about class definitions:

  • Class names (and hence object types) always begin with a capital letter, which helps distinguish them from primitive types and variable names.
  • You usually put one class definition in each file, and the name of the file must be the same as the name of the class, with the suffix .java. For example, the Time class is defined in the file named
  • In any program, one class is designated as the startup class. The startup class must contain a method named main, which is where the execution of the program begins. Other classes may have a method named main, but they will not be executed.

With those issues out of the way, let's look at an example of a user-defined type, Time.

Last Update: 2011-01-24