Object Creation
Objects in Java are allocated on a system “heap” memory
space. Unlike other languages, however, we needn’t manage that memory
ourselves. Java takes care of memory allocation and deallocation for you.
Java explicitly allocates storage for an object when you create it with
the new operator. More
importantly, objects are removed by garbage collection when they’re no
longer referenced.
Constructors
Objects are allocated with the new operator using an object
constructor. A constructor is a special method with the same
name as its class and no return type. It’s called when a new class
instance is created, which gives the class an opportunity to set up the
object for use. Constructors, like other methods, can accept arguments
and can be overloaded (they are not, however, inherited like other
methods; we’ll discuss inheritance in Chapter 6).
classDate{longtime;Date(){time=currentTime();}Date(Stringdate){time=parseDate(date);}...}
In this example, the class Date
has two constructors. The first takes no arguments; it’s known as the
default constructor. Default constructors play a
special role: if we don’t define any constructors for a class, an empty
default constructor is supplied for us. The default constructor is what
gets called whenever you create an object by calling its constructor
with no arguments. Here we have implemented the default constructor so
that it sets the instance variable time by calling a hypothetical method,
currentTime(), which ...