为什么Java构造函数中的`this.变量`没有被赋值为数组?

huangapple go评论69阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年10月22日 13:57:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/64476131.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定