The Anatomy of a Java Application |
Theimport java.util.Date; class DateApp { public static void main (String args[]) { Date today = new Date(); System.out.println(today); } }main()
method of theDateApp
application creates a Date object namedtoday
. This single statement performs three actions: declaration, instantiation, and initialization.Date today
declares to the compiler that the nametoday
will be used to refer to an object whose type is Date, thenew
operator instantiates new Date object, andDate()
initializes the object.Declaring an Object
Declarations can appear as part of object creation as you saw above or can appear alone like thisEither way, a declaration takes the form ofDate today;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 thetype namenew
operator.Instantiating an Object
Thenew
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 isA 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()that initializes the new Date to the year, month and day specified by the three parameters.Date(int year, int month, int day)
The Anatomy of a Java Application |