Since my post yesterday regarding constructing a link list from scratch I have made some progress.
I have encountered a new hurdle: storing an object within an object.
Lets say I have a 'book' class with the following attributes (forgetting all the set & get methods which I am familiar with):
private String title;
private int rating;
How would I then reference another class such as 'author' as obviously a book must have an author and many books may have the same or more then one author.
Here is my 'author' class attributes (again ignoring gets & sets):
String authorName;
String authorEmail;
Am I right in thinking I need to initiate an object of 'author' within the 'book' class as such:
private String title;
private int rating; //mine
private Author author = new Author();
Would I then have to set the attributes authorName and authorEmail everytime I made a new instance of 'book'?
Many thanks in advance for constructive feedback.
You don't necessarily need to instantiate the Author object right there where you declare the attribute. I would suggest something like passing in an already-instantiated Author either to the constructor of the Book class or to a setter. Then you could pass the same Author in to each Book you create that should be associated with it.
EDIT: added some code snippets:
For instance, if you made your Book constructor something like this:
public Book(String title, int rating, Author author) {
// set this.title, this.rating, and this.author to the passed-in parameters...
}
Then you would invoke it in code like this:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With