更改字段的类类型

时间:2015-01-02 13:36:19

标签: 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 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;
    }       
}

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

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

而不是

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

答案 1 :(得分:0)

课程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){