英文:
why the java constructor this. variable isn't being assigned to an array?
问题
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 I'm assigning the value to size from the constructor method?
英文:
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?
答案1
得分: 5
book_arr
实例变量在构造函数体执行之前进行了初始化,因此此时size
仍然是0
(默认值)。
你应该在构造函数内部创建数组实例,以便使用传递给构造函数的size
:
public class Library
{
private int size;
private Book[] book_arr;
public Library(int size) {
this.size = size;
this.book_arr = new Book[size];
}
}
详细说明一下,所有实例变量的声明和初始化在实例创建时执行,在构造函数体之前执行(无论它们是在构造函数之前还是之后出现)。另一方面,对于同一类型的两个语句,例如:
private int size = 5;
private Book[] book_arr = new Book[size];
将按照它们出现的顺序执行。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论