Previous | Next | Trail Map | Writing Java Programs | The Anatomy of a Java Application


Declaring, Instantiating and Initializing an Object

import java.util.Date;
class DateApp {
    public static void main (String args[]) {
        Date today = new Date();
        System.out.println(today);
    }
}
The main() method of the DateApp application creates a Date object named today. This single statement performs three actions: declaration, instantiation, and initialization. Date today declares to the compiler that the name today will be used to refer to an object whose type is Date, the new operator instantiates new Date object, and Date() initializes the object.

Declaring an Object

Declarations can appear as part of object creation as you saw above or can appear alone like this
Date today;
Either way, a declaration takes the form of
type name
where type is either a simple data type such as int, float, or boolean, or a complex data type such as a class like the Date class. name is the name to be used for the variable. Declarations simply notify the compiler that you will be using name to refer to a variable whose type is type. Declarations do not instantiate objects. To instantiate a Date object, or any other object, use the new operator.

Instantiating an Object

The new operator instantiates a new object by allocating memory for it. new requires a single argument: a constructor method for the object to be created. The constructor method is responsible for initializing the new object.

Initializing an Object

Classes provide constructor methods to initialize a new object of that type. In a class declaration, constructors can be distinguished from other methods because they have the same name as the class and have no return type. For example, the method signature for Date constructor used by the DateApp application is
Date()
A constructor such as the one shown, that takes no arguments, is known as the default constructor. Like Date, most classes have at least one constructor, the default constructor. However, classes can have multiple constructors, all with the same name but with a different number or type of arguments. For example, the Date class supports a constructor that requires three integers:
Date(int year, int month, int day)
that initializes the new Date to the year, month and day specified by the three parameters.


Previous | Next | Trail Map | Writing Java Programs | The Anatomy of a Java Application