1 回答

TA貢獻2036條經驗 獲得超8個贊
當這完成時Library:
private int capacity;
private Book[] books = new Book[capacity];
super()構造函數中的代碼尚未運行(這些初始化在最開始 [或在子類之后] 插入到構造函數中)。所以capacity有它的默認值,0。后來你分配給capacity,但為時已晚。
反而:
public class Library {
private int capacity;
private Book[] books; // *** Don't initialize it here
public Library(int capacity) {
if (capacity > 1) {
this.capacity = capacity;
}
else {
this.capacity = 4;
}
this.books = new Book[this.capacity]; // *** Initialize it here
}
但是這里還有另一個有用的東西要學。在遍歷數組或類似數組時,使用數組的大小知識,而不是其他信息源 ( capacity)。所以:
for (int x = 0; x < this.books.length ; ++x) {
// -----------------^^^^^^^^^^^^^^^^^
堅持真相的主要來源。capacity:-)(事實上,您可能根本不需要您的實例成員。)
添加回答
舉報