Java 更改字段的类类型

Java 更改字段的类类型,java,class,field,Java,Class,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

我被要求做下面的任务,作为一个关于课堂的初学者教程

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;
    }       
}
我不知道如何将author字段更改为User类型。看看其他教程,我似乎找不到一些对我来说非常基本的问题的答案:/

有什么建议吗?

而不是

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

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

上课时
Book
change
publicstringauthor
私人用户作者
和新的
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){

好了,看看您在哪里声明
作者
字段。声明的哪一部分是字段的类型?找到它,并将其更改为
User
。。。然后看看还有什么中断(例如,当传入值是
字符串时,从构造函数分配一个值)。现在还不清楚这里的问题是什么——任务的哪一部分给你带来了概念上的问题。@JonSkeet我不确定我做得是否正确?看起来我在声明author属于这两种类型,但我觉得我只需要在book类中进行更改,因为它告诉我要修改它。那么,我是否要从book类中删除
author
?不,您不会删除它-您要更改它的类型,就像说明中所说的那样。在
书籍
类中找到
作者
字段,并将其类型更改为
用户
。另一方面,我们不清楚为什么在
User
类中有一个
author
字段。(应该删除-用户没有作者…)changin constructors参数也需要Yes,注意到正如我发布的那样。谢谢