John Smith John Smith - 9 months ago 77
Java Question

How to resolve Stackoverflow error?

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;
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?

Answer Source

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.