gpt4 book ai didi

java - 从书类简单获取作者姓名

转载 作者:行者123 更新时间:2023-11-29 08:42:08 24 4
gpt4 key购买 nike

所以,我是面向对象编程的新手。我正在做下一个练习:

  1. 给定一个定义为具有以下属性的类 Book:

    Author author;
    String title;
    int noOfPages;
    boolean fiction;

    为每个属性编写标准的 get/set 方法 header 。

  2. [编码] 根据习题1中要求的属性和get/set方法实际编码编译Book类

    <

这是我的代码:

public class Author {

//private variable
private String name;
private String gender;
//constructor
public Author (String name, String gender){
this.name = name;
this.gender = gender;
}
//getters
public String getName(){
return name;
}
public String getGender(){
return gender;
}
public class Book {

//private variables
private Author author;
private String title;
private int noOfPages;
private boolean fiction;

//constructor
public Book(String title, int noOfPages, boolean fiction){
this.author=new Author ("Jacquie Barker","Female");
this.title = title;
this.noOfPages=noOfPages;
this.fiction = fiction;
}

//getters
public Author getAuthorsName(){
return this.author;
}
public String getTitle(){
return title;
}

public int getNoOfPages(){
return noOfPages;
}

public boolean getFiction(){
return fiction;
}

//setters
public void setAuthor(Author newAuthor){
author=newAuthor;
}
public void setTitle (String title){
this.title=title;
}
public void setNoOfPages(int noOfpages){
this.noOfPages=noOfpages;
}
public void setfiction(boolean fiction){
this.fiction=false;
}

public String toString(){
return "Title: " + this.title + "\n"+"Author: " + this.author + "\n" +
"No. of pages: " + this.noOfPages + "\n" + "Fiction: " + this.fiction;
}
}

这是主要的摘录:

Title: Beginning in Java Objects

Author: book.Author@15db9742

No. of pages: 300

Fiction: true

如您所见,该程序不会打印作者姓名。

感谢所有帮助!

最佳答案

这里有两个选择。首先,您可以简单地重构 Book.toString() 方法中的代码来打印作者的真实姓名:

public String toString(){
return "Title: " + this.title + "\n"+"Author: " + this.author.getName() + "\n" +
"No. of pages: " + this.noOfPages + "\n" + "Fiction: " +
}

其次,您可以覆盖 Author 类中的 toString() 方法以返回作者姓名。然后,您可以保留 Book.toString() 方法,因为当您尝试打印 Author< 时,Java 将调用此 toString() 方法 对象:

public class Author {
// print the author's name when an Author object appears in a print statement
public String toString() {
return this.name;
}
}

然后像你一样:

public class Book {
public String toString(){
return "Title: " + this.title + "\n"+"Author: " + this.author + "\n" +
"No. of pages: " + this.noOfPages + "\n" + "Fiction: " + this.fiction;
}
}

关于java - 从书类简单获取作者姓名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39216664/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com