There are three stages to creating an object :
1. Declaration 2. Instantiation 3. Initialization
We can declare the object variables in the same way as primitive variables. We use the
Socket class defined previously as our data type in this example. The name of the object variable is
At this point in time, no memory have been assigned as yet to store our object. The current value of the object is the special keyword
Instantiation and Initialization
The object is instantiated(created) in memory by using the
new keyword operator and the reference to the memory location is returned.
The call to the default, no-argument constructor then initializes the newly created object.
socket variable now holds a reference or points to the socket object in memory. We can now use the
socket object to access the
Socket class members using the dot operator, (
The reference returned from instantiation not have to be assigned to a variable, it can be used directly, e.g
null signifies the object is not associated with any memory.
null represents an uninitialized object, and can only be used for objects not primitive types. Memory for primitive types is not allocated using the
new keyword so they can never be
The fields in a class automatically get assigned to default values when an object is created.
|Data Type||Default Value|
Objects that are no longer used are automatically removed from memory. The process is called
garbage collection. This frees the programmer from manually managing memory as done in other programming languages like C and C++.
You can also hint for an object to be
garbage collected by assigning its reference to null.