You will learn about the following in this chapter:
The three different ways of initializing instance variables automatic initializations, initialization declarations, and constructors
The new keyword's ability to call a constructor
Overloading instance constructors
The constructor initializer
private instance constructors
The readonly class member
Garbage collection freeing the memory occupied by unreachable objects
The "Dispose design pattern" freeing other scarce, non-memory resources occupied by unreachable objects
Destructors and their limited use
Living organisms are conceived; they live for a certain period of time during which they occupy scarce resources (organic substances forming their tissues, water, and so on) so they can function, and eventually they die. Similarly, objects are created inside the computer memory; they have a lifetime where they occupy a part of the memory (and perhaps other scarce resources) so they can act and hold data, and then also they die.
Nature has a neat ecological system where dead bodies and debris are meticulously consumed by animals, such as hyenas, vultures, beetles, ants, worms, and microorganisms (natures garbage collectors). Not only does this system keep any area clear from debris, it also recycles otherwise trapped resources.
Unless dead objects are garbage collected and their memory freed, in a fashion similar to that of nature's painstaking reuse of every organic molecule, object corpses will soon fully occupy the computer memory, making it impossible for new objects to live here. As a consequence the computer eventually crashes unable to support the memory required to keep the new objects of the program alive. (Hmm…this turned out to be quite a morbid introduction, but I guess nothing less could be expected for a chapter carrying the number 13).
This chapter is about the creation and destruction of the objects that live inside a running computer program.