Creation and Initialization
Many OOP languages ( Smalltalk, C++,Java, objective-C) tie
together object creation and initialization.
-
Avoids creating an object without properly initializing
its fields
-
Avoid creating an object and initializing its fields
more than once
We discuss two mechanisms, classes(factory) methods and constructors.
Class Methods
-
smalltalk and object Pascal use "object creators" to initialize
objects at creation
As in ++, a Constructor in java is a method ( i.e. member
function)
-
has same name as a class
-
can take argument lists., like function.
-
invoked implicitly by new, explicitly by this in other constructors
class newClass {
. . . . . . .
newClass ( int i ) {
. . . // initialization
}
}
Destructors in java
-
Garbage collection recovers memory no longer referenced
-
method finalize ( ) ,if defined, called when reclaiming memory
for object
-
Does any other "housecleaning" needed (close files, etc.)
- Executes at unpredictable time
- Should not be depended upon for correctness - do critical ' housecleaning"
tasks explicitly