Creating Objects

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 socket.

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 null.

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.

The 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

new Socket().connect();

null Keyword

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 null.

Default Values

The fields in a class automatically get assigned to default values when an object is created.

Data Type Default Value
byte 0
short 0
int 0
long 0L
float 0.0F
double 0.0D
char '\u0000'
any object null
boolean false

Garbage Collection

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.

results matching ""

    No results matching ""