简体   繁体   中英

How to call a value from another class with 3 java classes

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

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

public String toString() {
    return this.lastName +", "+ this.firstName;
}

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);   
   }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM