2.7 Example: Definition of the class Book - version
2
/*
+---------------+
| Book | +-------------+
+---------------+ +-->| Author |
| String title | | +-------------+
| Author author |- + | String name |
| int price | | int dob |
| int year | +-------------+
+---------------+
*/
// to represent an author of a book
class Author {
String name;
int dob;
Author(String name, int dob) {
this.name = name;
this.dob = dob;
}
}
// to represent a book with author
class Book {
String title;
Author author;
int price;
int year;
Book(String title, Author author, int price, int year) {
this.title = title;
this.author = author;
this.price = price;
this.year = year;
}
}
/* Interactions:
Examples of the use of the constructor for the class Author
Author mf = new Author("Matthias",1900);
Author pc = new Author("Pat Conroy", 1940);
Examples of the use of the constructor for the class Book - version 2
Book b1 = new Book("HtDP", mf, 60, 2001);
Book b2 = new Book("Beach Music", pc, 20, 1996);
Examples of the use of the selectors in the class Book - version 2
b1.title -- expected: "HtDP"
b1.author -- expected: new Author("Matthias",1900)
b1.author.name -- expected: "Matthias"
b1.author.dob -- expected: 1900
b1.price -- expected: 60
b1.year -- expected: 2001
b2.title -- expected: "Beach Music"
b2.author -- expected: new Author("Pat Conroy", 1940)
b2.author.name -- expected: "Pat Conroy"
b2.author.dob -- expected: 1940
b2.price -- expected: 20
b2.year -- expected: 1996
*/