Format:
ObjectType Identifier = new ObjectType(Parameters if any);
'new' is a keyword that calls the constructor of the class.
Consider the following class called NetworkUser:
To create an object from this class, we must declare a new NetworkUser. Each object we create from the class must have a unique identifier/name. The following code instantiates 3 NetworkUser objects, and calls a couple of their methods:
The following output is produced:
Object arrays
Alternatively, the NetworkUsers could be stored in an array and we could loop through each one to display their credentials:
The first statement instantiates an array of type NetworkUser. Only objects of type NetworkUser can be stored in the array. The array has a length of 3 which means that the first index (position) is 0 and the final is 2.
The next 3 statements instantiate a NetworkUser object directly into each index of the array. CurrentUsers[0] is a reference to the first index of the array called currentUsers. This is followed by the assignment operator (=) which is then followed by the object that will be stored in this index.
The for loop is primed to loop for as many times are there are indexes in the currentUsers array - the loop counter (x) starts at 0 (the same as the first index of the array) and is incremented on each pass of the loop by 1 until it reaches 2 (the final index of the array).
The print statements inside of the loop get the current NetworkUser in the array by using the statement currentUsers[x].
On the first pass of the loop, this will return the NetworkUser object at currentUsers[0].
On the second pass of the loop, this will return the NetworkUser object at currentUsers[1].
On the third pass of the loop, this will return the NetworkUser object at currentUsers[2].
All that's left to do is call the methods of NetworkUser. In this case, getUserName() and getPassword() are called.
Here's what the output looks like:
See more at pastebin.
Err, here's a cat (at animals[2]):















