Reputation: 213
public class Library {
private int size;
public Library(int size) {
this.size = size;
}
Book book_arr[]= new Book[size];
Using the size variable for array isn't being initiated , why not since im assigning the value to size from the constructor method?
Upvotes: 1
Views: 49
Reputation: 393936
The book_arr
instance variable is initialized before the constructor body is executed, so size
is still 0
(by default) at that time.
You should create the array instance inside the constructor, in order to use the size
passed to the constructor:
public class Library
{
private int size;
private Book[] book_arr;
public Library(int size) {
this.size = size;
this.book_arr = new Book[size];
}
}
To elaborate, all instance variable declarations and initializers are executed when an instance is created, just before the constructor body (regardless if they appear before or after the constructor). On the other hand, two statements of the same type, such as:
private int size = 5;
private Book[] book_arr = new Book[size];
will be executed in the order they appear.
Upvotes: 5