更改字段的 class 类型

Change class type for field

我需要完成以下课程初学者教程的任务。

1) Create a class called User.
  a) Add fields for name, age, and location.
  b) Add a method called toString.
2) In the book class:
  a) Change the author field to be of type User.
  b) Modify the toString method to include the author's name.

下面是我的代码

public class User {
    public String name;
    public int age;
    public String location;
    public String author;

    public String toString() {
        String description1 = "Name:" + name + " Age:"+ age + " Location:" + location + " Reading:" + author; 
        return description1;
    }

}

public class Book {

    public String title;
    public String author;
    public int numPages;
    public int isbn;

    public Book(String title, String author, int numPages, int isbn){
        this.title = title;
        this.author =  author;
        this.numPages = numPages;
        this.isbn = isbn;
    }

    public String toString() {
        String description = "Title:" + title + "Author"+ author + "Num. of pages" + numPages + "ISBN" + isbn; 
        return description;
    }       
}

我不确定如何将作者字段更改为用户类型。查看其他教程,我似乎无法找到对我来说非常基本的东西的答案:/

有什么建议吗?

而不是

public String author;

你会用

public User author;

因此您的构造函数更改为

public Book(String title, User author, int numPages, int isbn){
    this.title = title;
    this.author =  author;
    this.numPages = numPages;
    this.isbn = isbn;
}

而不是

public String toString() {
    String description = "Title:" + title + "Author"+ author + "Num. of pages" + numPages + "ISBN" + isbn; 
    return description;
}

你会用

public String toString() {
    String description = "Title:" + title + "Author"+ author.name + "Num. of pages" + numPages + "ISBN" + isbn; 
    return description;
}

在 class Book 中将 public String author; 更改为 private User author; 并且新的 toString() 将如下所示:

public String toString() {
    String description = "Title:" + title + "Author"+ author.getName() + "Num. of pages" + numPages + "ISBN" + isbn; 
    return description;
} 

并且构造函数也应该改为:

public Book(String title, User author, int numPages, int isbn){