University of Toronto - Fall 2000
Department of Computer Science

Week 4 - Static

Book Class Example

For example, consider adding a static variable to our Book class that will hold the number of different titles in our collection. Create a static variable called numTitles and a static method called getNumTitles( ). In addition to the methods in our original Book class, we would have:

class Book {
	private int numCopies;
	private String title;
	private static int numTitles = 0;

	/**
	* construct a new book with title 't'
	*/
	public Book (String t) {
		title = t;
		numTitles++;
	}

	/**
	 * return number of different books in the collection.
	 */
	public static int getNumTitles () { 
		return numTitles;
	}
    }

 public class Library {
	public static void main (String[] args) {	
		Book b1 = new Book ("The Hobbit");
		int x;
		x = Book.getNumTitles();
		Book b2 = new Book ("The Firm");
		b2.buyCopies(5);
		x = Book.getNumTitles();
	}
}

Where should we store numTitles in the memory model? It doesn't go in the call stack area because it is part of the Book class and continues to exist regardless of what is happening in main(). It shouldn't go inside a Book object because it doesn't belong to an individual Book, but to all of them. So we draw a new area in our model called the Static Space. In this space we draw a box for each class in the program, and list all static variables and methods for each class.

Show what happens in memory...