Memory allocation

The memory is composed of two main areas, the stack and the heap. When an object is instantiated, its memory fragment is allocated from the heap.

In the program above, on line 7, we instantiate the ClassB and allocate a fragment of memory by using the new key word followed by a special function call whose name is the same as its class.This special function is called constructor.

The instantiation returns a reference pointing to that fragment which is finally stored in the objectB variable.

By default, each class has a hidden constructor that takes no argument, however,we could explicitly define it.

Sometimes, we are constrained to write it especially when we define other constructors that have arguments. if we don't and try to instantiate an object with it, it won't compile.

the code below doesn't compile because of line 7, we instantiate ClassB with an undefined constructor.

Initialization order

When an object is instantiated, its internal fields are initialized following the order in which they are declared except the fields that are initialized inside the constructor, they are initialized at the end of the process.