So I'm practictising Object oriented programming and I'm trying to make a Book class that can have multiple authors but I don't know how to do it.
This is the UML of the excerise:
This is my author class which works fine:
public class Author {
//attributen van de class auteur
private String name;
private String email;
private char gender;
//constructor
public Author (String name, String email, char gender){
this.name = name;
this.email = email;
this.gender= gender;
}
//methodes
public String getName(){
return name;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public char getGender(){
return gender;
}
//methode om gegevens van autheur opbject op te halen
public String toString(){
return "Author[name = " + name + ", email = " + email + ", gender = " + gender + "]";
}
}
And here is the Book class that I tried to make:
public class Book {
//attributes
private String name;
private Author authors [] = new Author[2];
private double price;
private int qty = 0;
public Book(String name, Author authors[], double price, int qty) {
this.name = name;
authors[0] = new Author("Tan Ah Teck", "AhTeck@somewhere.com", 'm');
authors[1] = new Author("Paul Tan", "Paul@nowhere.com", 'm');
this.price = price;
this.qty = qty;
}
public String getName() {
return name;
}
public Author getAuthors() {
return authors[authors.length];
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public String toString() {
return "Book [name = " + name + " authors = " + authors[0] + " email = " + authors[0].getEmail() + " price = " + price + " qty = " + qty + "]";
}
//methodes om gegevens van de autheur op te halen
public String getAuthorNames() {
return authors[].getName();
}
public String getAuthorEmails() {
return authors[].getEmail();
}
public char getAuthorGenders() {
return authors[].getGender();
}
}
So when I try to make an object of a book in my main.java the constructor of the book class is not working.
Also at this function : public Author getAuthors() {
it says: Array index is out of bounds.
Also at the methods to get the author names, emails and genders it says: Unknown class authors[].
How can I modify this book class so a book can have one or more authors? (the Book class did work when a book only could have 1 author, but now I'm trying to change it so a book can have more authors)
Any kind of help is appreciated!