University of Toronto - Fall 2000
Department of Computer Science

Week 2 - Multiple Objects

More Than One Object

Program Example

First let's add an instance variable to store the title of our book, and methods that can be used to set the title of the book and to retrieve the title of the book.

	class Book {

		// in addition to the code already written
		private int numCopies;
		private String title;

		public void setTitle (String t) {
			title = t;
		}

		public String getTitle() {
			return title;
		}
	}

Now create a program that creates two book objects.

	public class Library {

		public static void main(String[] args) {
			Book b1 = new Book();
			b1.setTitle("Angela's Ashes");
			b1.buyCopies(2);

			Book b2 = new Book();
			b2.setTitle("Side Effects");

			System.out.println ("Book list: ");
			System.out.println (b1.getTitle() +
					" " + b2.getTitle());
		}
	}

Let's trace the code using the memory model. Notice how the title variable stores different values for different objects.

Memory Model

Note: All methods have not been included for each object. For example, the prototype for every method in the Book class should be written in each Book object that we show in our memory model diagram.

By showing all instance variables and method prototypes within each object, it reminds us of the what information (instance variables) and actions (methods) are available for each object.