Object lifetime

Creation of an object is generally deterministic, but destruction varies by programming context.

Notably, in a garbage-collection environment, objects are destroyed when the garbage collector chooses.

In many contexts, including C++, C# and Java, an object is created via special syntax like new typename().

In C# and Java, with no explicit destruction syntax, the garbage collector destroys unused objects automatically and non-deterministically.

Life cycle generally includes memory management and operations after allocation and before deallocation.

Like other methods, a constructor can be overloaded in order to support creating with different initial state.

In class-based languages with deterministic object lifetime, notably C++, a destructor is called when an instance is deleted, before the memory is deallocated.

They cannot be overloaded, must have no arguments, need not maintain class invariants, and can cause program termination if they throw exceptions.

The period between when initialization completes to when finalization starts is when the object is both alive and in a consistent state.

In class-based programming, object creation is also known as instantiation (creating an instance of a class).

Creation and destruction can be customized via a constructor and a destructor and sometimes with separate initializer and finalizer methods.

Further, constructors and initializers often can accept arguments, while destructors and finalizers generally do not as they are often implicitly callable.

A Java class can be declared with defaults as: After an instance is created (i.e. new Foo()) it lives until it has no references and the garbage collector deletes it.