Object Creation
Objects in Java are allocated from a
system heap space, much like malloc‘ed
storage in C or C++. Unlike in C or C++, 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 by specifying the new operator with 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).
class Date {
long time;
Date( ) {
time = currentTime( );
}
Date( String date ) {
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access