Stella
Stella

Reputation: 1868

Error accessing 2 object reference each other in Java

I have created two POJO classes Author and Book. Where Author POJO class requires Book as an argument and Book POJO requires Author as an argument, i.e., both are bidirectionally related/circularly dependent.

Author Pojo class:

Public class Author{
Private Book book;
Private String authorname;
publicIndividual(Book book, String authorname){
this.authorname=authorname;
this.book = book
}
// getters and setters…
}

Book pojo class:

Public class Book{
Private Author author;
Private String bookname;
Private String id;
publicIndividual(String id, String bookname, Author author){
this.id=id
this.bookname = bookname;
this.author = author
}
// getters and setters…
}

Java Class to set data:

public final Author author = new Author(book, authorname);
public final Book book = new Book(id, bookname, author);

I am facing error "Illegal forward reference" since trying to call book method before it is initialized. How to achieve this incase of interdependent pojo classes?

Upvotes: 0

Views: 129

Answers (1)

Traian GEICU
Traian GEICU

Reputation: 1786

Mainly since you have cross-reference you could just instantiate with null one reference and after set up properly.

public class TestRef
{
    public static void main(String args[])
    {
        Author author = new Author(new Book("1","bookname",null), "authorname");
        System.out.println(author+" Book.author::"+author.book.author);
        author.book.author=author;
        System.out.println(author+" Book.author::"+author.book.author);
    }
    static class Author{
        Book book;
        String authorname;
        public Author(Book book, String authorname)
        {
            this.authorname=authorname;
            this.book = book;
        }
        public String toString()
        {
            return "Author("+book+","+authorname+")";
        }
    }
    static class Book{
        Author author;
        String bookname;
        String id;
        public Book(String id, String bookname, Author author){
        this.id=id;
        this.bookname = bookname;
        this.author = author;
        }
        public String toString()
        {
            return bookname+"_"+id;
        }
    }   
}

Output

//with null ref on Book for Author
Author(bookname_1,authorname) Book.author::null
//after set up properly ref
Author(bookname_1,authorname) Book.author::Author(bookname_1,authorname)

Upvotes: 1

Related Questions