Instantiation

From TRCCompSci - AQA Computer Science
Revision as of 12:13, 15 December 2016 by Mohkale (talk | contribs) (Definition)
Jump to: navigation, search

Instantiation

Definition

Instantiation is the process of allocating a block of memory to a new object instance. Instantiation is the direct process of declaring a new object by ClassName, giving it an identifier Name, and in some cases passing initialization arguments to the new object. For Example:

1 int[] intArray = new int[5] // Allocates new int array a block of memory

The above code extract shows the process of declaring a new integer Array, and assigning it to hold 5 items of type integer (using the assignment operator '='). In the background of the program a block of memory large enough to hold 5 integers is allocated to this array and referenced to via the name 'intArray'. The important point here is that the Object instance isnt actually instantiated until it is assigned to, hence if someone tried to do the following:

1 int[] intArray; // Declares a variable called intArray of type integer array
2 Console.WriteLine(intArray[0]);

An error will be produced due to intArray not referencing anything in memory. Subsequently if 'intArray' is assigned to a new object instance after declaration, the program would work fine.

1 int[] intArray; // Declares a variable called intArray of type integer array
2 intArray = new int[5]; // Assigns variable intArray to a new object instance of type Array with Length 5
3 Console.WriteLine(intArray[0]); // Will output Null