[英]How to call a value from another class with 3 java classes
我有 3 个名为 Author、Book 和 DisplayBook 的 Java 类。 Author 类用于设置作者姓名。 Book 类用于获取书籍的详细信息(书名、作者、价格),DisplayBook 类用于在控制台窗口中显示输出(书名、作者、价格)。
这是我到目前为止所做的,但它为作者显示了一个随机文本(Author@2f2c9b19)。 这些是我的代码,分别带有 set 和 get 方法。
作者类
private String firstName;
private String lastName;
public Author(String fname, String lname)
{
firstName = fname;
lastName = lname;
}
图书类
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);
}
显示书类
public static void main(String[] args) {
Author author = new Author("Jonathan", "Rod");
Book book = new Book("My First Book", author, 35.60);
book.printBook();
}
这是输出
如何让Jonathan Rod
显示在Author:
旁边?
覆盖Author
类的 toString 方法。 也许像这样:
public String toString() {
return this.lastName +", "+ this.firstName;
}
它显示 Author@2f2c9b19 的原因是因为当您将整个对象传递到打印中时,Java 正在显示该对象的内存地址。
你的印刷书应该是这样的
public void printBook()
{
System.out.print("Title: " + title + "\nAuthor Name: " + author.firstName + " " + author.lastName + \nPrice: " +
price);
}
每当您打印任何对象时,它都会调用 toString 方法。 在这里,您没有获得理想的输出,因为它在 Author 上调用 toString ,这在您的类中未被覆盖。 请覆盖 Author 类中的 toString 方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.