next up previous contents
Next: Inheritance Up: Encapsulation Previous: Messages   Contents

Constructors, Destructors, and Garbage Collection

The allocation, reclamation, and reuse of dynamic memory from the heap is an important aspect of most object-oriented programs, and some non-object-oriented programs as well.

Any particular language or language platform, like JAVA virtual machine, should do some operation in memory:

Failure to deal with this important issue results in a condition often referred to as "memory leakage."

Constructors
are used to instantiate and possibly initialise an object:
	// instantiate an object of the class cat
	cat mour  = new cat();

Constructors can be overloaded just like other methods in JAVA. Overloading will be discussed later. Briefly, method overloading means that two or more methods can share the same name. Compiler determines version depends on the list of actual parameters.

In this particular statement, the new operator is used to allocate dynamic memory from the heap, and also as the constructor to construct the object in that memory space. The address of the memory containing the object is returned and assigned to the reference variable named mour. If the memory cannot be allocated, an exception will be thrown.

In JAVA you do not define a constructor when you define a new class, a default constructor that takes no parameters is defined on your behalf.

You can also define your own constructor with no argument needed. Defining a constructor is similar to defining a method, but must have the same name as the class, do not have a return type and must not have return statements.

The following code fragment shows the important parts of a JAVA program, similar to the previous one which has been modified to use a parameterised constructor.

  ...
     String name;
    // Parameterised constructor
    cat (String n) {
	name=n;}
  ...
	System.out.println("This cat named " + 
			   name + 
			   " has child(ren): " 
			   + child);
  ...   
   cat mour = new cat("Pirat");
  ...

Destructors

A destructor is a special method typically used to perform cleanup after an object is no longer needed by the program. C++ supports destructors, but JAVA does not support destructors.

JAVA supports another mechanism for returning memory to the operating system when it is no longer needed by an object.

Garbage Collection

The garbage collector is a part of the runtime system that runs in a low-priority thread reclaiming memory that is no longer needed by objects used by the program. An object becomes eligible for garbage collection in JAVA when there are no longer any reference variables that reference the object.


next up previous contents
Next: Inheritance Up: Encapsulation Previous: Messages   Contents
Olexiy Ye. Tykhomyrov 2001-12-16