如何在Java中正确初始化列表成员对象

时间:2016-08-16 03:36:18

标签: java android list oop constructor

我有这堂课:

public class Book extends SugarRecord {
    private Long id;
    private String mBookName;
    private String mAuthorName;
    private List<Page> mPageList;

    public Book() {

    }

    public Book(String bookname, String authorName) {
        mBookName = bookname;
        mAuthorName = authorName;
        mPageList = new ArrayList<>();
    }

    public Book(String bookname, String authorName, List<Page> pageList) {
        mBookName = bookname;
        mAuthorName = authorName;
        mPageList = pageList;
    }

    @Override
    public Long getId() {
        return id;
    }

    @Override
    public void setId(Long id) {
        this.id = id;
    }

    public String getAuthorName() {
        return mAuthorName;
    }

    public void setAuthorName(String authorName) {
        mAuthorName = authorName;
    }

    public String getBookName() {
        return mBookName;
    }

    public void setBookName(String bookName) {
        mBookName = bookName;
    }

}

Page类并不多,但以防万一:

public class Page {
    private Long id;
    private String mText;

    public Page() {

    }
    public Page(String text) {
        mText = text;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getText() {
        return mText;
    }

    public void setText(String text) {
        mText = text;
    }
}

现在我认为有两个构造函数是有意义的,如果你已经有页面就有一个,如果你没有页面就有一个,但是这是正确的方法吗?或者我是否需要复制构造函数中的ArrayList而不仅仅是引用它?

0 个答案:

没有答案