自从我昨天关于从头开始构建链接列表的帖子以来,我已经取得了一些进展。
我遇到了一个新的障碍:在对象中存储对象。
假设我有一个具有以下属性的“book”类(忘记所有我熟悉的set & get方法):
private String title;
private int rating;那么我如何引用另一个类,比如' author‘,因为很明显,一本书必须有一个作者,许多书可能有相同的或多个作者。
下面是我的'author‘类属性(同样忽略get&set):
String authorName;
String authorEmail;我认为我需要在'book‘类中初始化一个'author’对象,对吗?
private String title;
private int rating; //mine
private Author author = new Author();那么,我是否必须在每次创建“book”的新实例时都设置属性authorName和authorEmail?
非常感谢您提供的建设性反馈。
发布于 2011-12-07 05:19:56
您不一定需要在声明属性的位置实例化Author对象。我建议将一个已经实例化的作者传递给Book类的构造器或setter。然后,您可以将相同的作者传递给您创建的每个应该与其关联的Book。
编辑:添加了一些代码片段:
例如,如果您的Book构造函数是这样的:
public Book(String title, int rating, Author author) {
// set this.title, this.rating, and this.author to the passed-in parameters...
}然后,您可以在如下代码中调用它:
Author bob = new Author();
// You can set the name and email of the Author here using setters,
// or add them as args in the Author constructor
Book firstBook = new Book("The First Book", 1, bob);
Book secondBook = new Book("The Second Book", 2, bob);发布于 2011-12-07 05:18:29
这是一个多对多的关系。你需要你的Author类仅仅是一个人和一本书之间的链接。然后事情就会解决了。
发布于 2011-12-07 05:19:05
您可能需要某种类型的单例作者列表,以防止同一作者的多个副本。否则,您肯定需要重写author的equals方法。
如果使用单例,可以在AuthorList对象中有一个getAuthor例程,该例程可以在作者不存在的情况下创建作者,也可以获取已经创建的作者。
https://stackoverflow.com/questions/8406928
复制相似问题