Im new to java and bluej. Now i tried to generate a new Book right after another Book is initialized:
public Book(String bookAuthor, String bookTitle)
{
author = bookAuthor;
title = bookTitle;
generatebook2();
}
public void generatebook2(){
Book book2 = new Book("Jumbo","Fary");
}
Somehow this wont work and i get a error:
Stackoverflow error: null
What did i wrong or how can i generate a new book onfly?
What you have created is an infinite loop. In your Book
constructor, you're creating a new Book
object which calls that new object's constructor, which creates a new Book
object...and so on and so on.
If you want to create another Book
object immediately after the first, you'll need to call that from outside the object, from wherever you created the book in the first place.
Something like this:
Book book1 = new Book("John Smith", "Book1");
Book book2 = new Book("John Smith", "Book2");
And remove the generateBook2
in the constructor.