You know what an Object is, and you also know what an Array is, but did you know that you can have an Array of Objects? This means that you could have an array that is a address book; holding objects that represent people in the book. These people will have primitive variables for their address and their phone number. In this post, I will teach you how to use objects in arrays. For this post, I will use the example of people in a phone book.
To create the phone book, you would type:
person[] phoneBook;
This will create an array of people, named phoneBook. Because I did not give phoneBook a size, it is currently pointing to null (nothing). We can fix this problem by saying:
phoneBook = new person[numberOfPeople];
This will give phoneBook the ability to hold numberOfPeople people. What would happen if we then tried to print the elements of phoneBook? Well, we would just print null a bunch of times in a row. To fix this problem, we would need to create a for loop to go through each element of phoneBook and fill them all with the default person. To fill an element of the array with a new person, you would type:
phoneBook[index]= new person();
Now if I wanted to have a value for the person's name, address, and phone number, I would type:
phoneBook[index]= new person(name, address, phoneNumber);
To call a method from a person in phoneBook, I would put phoneBook[index]. and then the method that I want to use. This would allow for me to access the names, addresses, and phoneNumbers of each person in phoneBook.
This is more or less all that you need to know about arrays of objects. Hopefully you have learned a thing or two about java, and I will see you again next week!
No comments:
Post a Comment