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
How do I get Jonathan Rod
to display beside Author:
?
CodePudding user response:
Override the toString method of the Author
class. Perhaps like so:
public String toString() {
return this.lastName ", " this.firstName;
}
CodePudding user response:
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);
}
CodePudding user response:
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.