0

I have 3 java class named Author, Book, and DisplayBook. Author class is for setting the name of the author. Book class is for geting details(title, author, price) of the book and DisplayBook is for displaying the output (title, author, price) in the console window.

This is what I have done so far but it displays a random text (Author@2f2c9b19) for the author. These are my codes with respective set and get methods.

Author class

private String firstName;
private String lastName;

public Author(String fname, String lname) 
{
   firstName = fname;
   lastName = lname;
}

Book class

private String title;
private Author author;
private double price;

public Book(String bTitle, Author bAuthor, double bPrice) 
{
   title = bTitle;
   author = bAuthor;
   price = bPrice;
}

public void printBook()
{   
   System.out.print("Title: " + title + "\nAuthor: " + author + "\nPrice: " + price);   
}

DisplayBook class

public static void main(String[] args) {
   Author author = new Author("Jonathan", "Rod");
   Book book = new Book("My First Book", author, 35.60);
   book.printBook();
}

This is the output

enter image description here

How do I get Jonathan Rod to display beside Author: ?

WiloWisk
  • 137
  • 3
  • 10
  • 2
    You could override [`#toString()`](https://www.baeldung.com/java-tostring). – sp00m Oct 18 '21 at 09:11
  • 2
    Does this answer your question? [How do I print my Java object without getting "SomeType@2f92e0f4"?](https://stackoverflow.com/questions/29140402/how-do-i-print-my-java-object-without-getting-sometype2f92e0f4) – OH GOD SPIDERS Oct 18 '21 at 09:15

3 Answers3

3

Override the toString method of the Author class. Perhaps like so:

public String toString() {
    return this.lastName +", "+ this.firstName;
}
polo-language
  • 826
  • 5
  • 13
1

The reason it is displaying Author@2f2c9b19 is because Java is displaying the memory address of that object as you are passing a whole object into the print.

your print book should look like this,

public void printBook()
   {   
      System.out.print("Title: " + title + "\nAuthor Name: " + author.firstName + " " + author.lastName + \nPrice: " + 
   price);   
   }
MrSpeedy
  • 51
  • 1
  • 5
0

whenever you just print any object , it calls toString method on that. Here you are NOT getting desirable output as its calling toString on Author which is not overrident in your class. Please override toString method in Author class.

Tushar F
  • 11
  • 2