简体   繁体   English

如何使用 3 个 java 类从另一个类调用值

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

I have 3 java class named Author, Book, and DisplayBook.我有 3 个名为 Author、Book 和 DisplayBook 的 Java 类。 Author class is for setting the name of the author. 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. Book 类用于获取书籍的详细信息(书名、作者、价格),DisplayBook 类用于在控制台窗口中显示输出(书名、作者、价格)。

This is what I have done so far but it displays a random text (Author@2f2c9b19) for the author.这是我到目前为止所做的,但它为作者显示了一个随机文本(Author@2f2c9b19)。 These are my codes with respective set and get methods.这些是我的代码,分别带有 set 和 get 方法。

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: ?如何让Jonathan Rod显示在Author:旁边?

Override the toString method of the Author class.覆盖Author类的 toString 方法。 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.它显示 Author@2f2c9b19 的原因是因为当您将整个对象传递到打印中时,Java 正在显示该对象的内存地址。

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.每当您打印任何对象时,它都会调用 toString 方法。 Here you are NOT getting desirable output as its calling toString on Author which is not overrident in your class.在这里,您没有获得理想的输出,因为它在 Author 上调用 toString ,这在您的类中未被覆盖。 Please override toString method in Author class.请覆盖 Author 类中的 toString 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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