How-To: Initialise arrays of objects in Java

You might think, like I did, that if you create an array of objects in Java then the constructor is automatically called on each object as part of the array creation process. But you’d be wrong.

Creating an array merely creates the object references – you have to instantiate each “inner” object in the array as a separate step if you want to be able to, ya know, do stuff… I think this is because in Java an array is an object – like, quite literally a single object that can be passed around like a single thing.

An example, perhaps?

Person Class

public class Person
{
	private int number = -1; // Each person gets a default number of -1 on creation
 
	// Default constructor
	public Person()
	{
		// The number property is left as -1 as per the default value specified above
	}
 
	// One parameter constructor which overwrites the default number value with a specified value
	public Person(int theNumber)
	{
		number = theNumber;
	}
 
	public void displayNumber()
	{
		System.out.println("My person number is: " + number);
	}
}

PersonTestDrive Class

public class PersonTestDrive
{
	final static public int MAX_PEOPLE = 3;
 
	public static void main(String[] args)
	{
		// Create an array of people. You're not creating any new People objects here - you're creating a new Array object
		Person[] people = new Person[MAX_PEOPLE];
 
		// *** INCORRECT : The Person objects in the people array don't exist yet! They're only references at this point! ***
		// for (Person tempPerson : people)
		// {
		// 	tempPerson.displayNumber(); // This doesn't give "-1" for each person, it gives a NullPointerException!
		// }
 
		// *** CORRECT : Instantiate each Person object in the array before accessing them! ***
		for (int loop = 0; loop < MAX_PEOPLE; loop++)
		{
			people[loop] = new Person(loop+1); // Create the Person object, setting the number property in this case
 
			people[loop].displayNumber();      // Now it'll output "My person number is: 1" etc. as expected
		}
	}
}

An introduction to ActionScript 3.0 – week 4 lesson 2

Learning actionscript? Want to know the gist of object creation and extending classes to do neat things? Then you’ve come to the right place…

Flash Week 4 Lesson 2

Download slides link: An Introduction to ActionScript 3.0 – Week 4, Lesson 2
Audience: Beginners who know a little about variables and how to perform some basic programming math.
Format: Powerpoint 2003 (so they can be opened in LibreOffice/OpenOffice, MS Office 2K3/2K7/2K10 etc.)
Template: OOo2 by Chih-Hao Tsai
Content License: These slides are released under a creative commons non-commercial attribution share-alike 3.0 license by me (r3dux) and come with no guarantee of correctness, fitness for purpose or anything of the sort.

EnJoY!