Design recipes for defining classes that represent self-referential data and mutually-referential data. Designing complex class hierarchies.
A List of Books is one of:
an MtLoB - an empty list of books
a ConsLoB consisting of a fst (a Book) and rst (a List of Books)
// to represent a book
class Book {
String title;
String authorName;
int price;
int year;
Book(String title, String authorName, int price, int year) {
this.title = title;
this.authorName = authorName;
this.price = price;
this.year = year;
}
}
/* +------+
| ALoB |<------------+
+------+ |
+------+ |
/ \ |
--- |
| |
--------------- |
| | |
+-------+ +----------+ |
| MtLoB | | ConsLoB | |
+-------+ +----------+ |
+-------+ | Book fst | |
| ALoB rst |----+
+----------+
*/
// to represent a list of books
abstract class ALoB {
}
// to represent an empty list of books
class MtLoB extends ALoB {
MtLoB() {
}
}
// to represent a constructed list of books
class ConsLoB extends ALoB {
Book fst;
ALoB rst;
ConsLoB(Book fst, ALoB rst) {
this.fst = fst;
this.rst = rst;
}
}
/* Interactions:
Examples of the use of the constructor for the class Book
Book b1 = new Book("HtDP", "Matthias", 60, 2001);
Book b2 = new Book("Beach Music", "Conroy", 20, 1996);
Examples of the use of constructors for the subclasses of ALoB
MtLoB mtLoB = new MtLoB();
ConsLoB lob1 = new ConsLoB(b1, mtLoB);
ConsLoB lob2 = new ConsLoB(b2, lob1);
Examples of the use of the field selectors for the subclasses of ALoB
lob1.fst -- expected: new Book("HtDP", "Matthias", 60, 2001)
lob1.rst -- expected: new MtLoB()
lob2.fst -- expected: new Book("Beach Music", "Pat Conroy", 20, 1996)
lob2.rst -- expected: lob1
// Note: lob1.fst.title, lob1.fst.name, etc. is not legal!!! WHY??
*/