It seems a little foolish to have to instantiate a book and then separately call a method to give it a title each time.
Since every book in our library will have a title, it would be better to specify the title automatically as part of the process of instantiating a book.
class Book { private int numCopies; private String title; /** * construct a book with title t * @param t my title */ public Book (String t) { title = t; } }
To instantiate a new book with title, "Anne of Green Gables":
public class Library { public static void main(String[] args) { Book b1 = new Book("Anne of Green Gables"); } }
Trace with the memory model
(a) showing the String title as an object
(b) using the short form to represent it like we do primitive types
(this is really cheating, but this is what we'll usually do.)
When the constructor is called, we draw a frame in the Method Stack, which contains the information about the constructor, including new variables created in the constructor (such as local variable t).