Java基础知识 - 对象的实例化[重复]

问题描述 投票:-1回答:4

这个问题在这里已有答案:

我正在学习Java并遇到了这段代码。有一个答案,但我不完全理解它是如何工作的。

我有一堂课

class Books {
   String author;
   String title;
}

然后我有测试课

class TestForBook {

   Books[] myBooks = new Books[3]; // doubt : 1
   System.out.println('myBooks length is ::' + myBooks.length);//prints 3. Its correct.

  myBooks[0].title = 'Book1 title'; // This throws null pointer exception

  myBooks[0] = new Books();
  myBooks[0].title = 'Book1 title'; //works fine after above line
}

我想理解为什么即使在声明类型为Books的数组后,数组值也为null(怀疑:注释中的1,我指的是那一行)。

我不知道我缺少什么Java的概念。以及如何/从哪里可以学习这些主题。任何资源或书籍建议也会很明显。谢谢。

这不是问题ID的重复:1922677。那里有解决方案(我也给出了解决方案),但我想知道为什么会这样。我的意思是,即使在宣布之后,为什么它为null也是我的问题。

java
4个回答
4
投票

在创建对象数组时,请记住new命令适用于数组,该数组最初将包含用于保存对象的请求槽,但不会被任何特定对象填充。这意味着,为了拥有3本书的数组,您需要

  • 创建一个数组对象,可以容纳3本书new Book[3]
  • 创建3个Book对象new Book(),并将它们放入数组中(每个插槽中一个)

3
投票

这是因为你刚刚创建了一个大小(长度)为3的空数组。

Books[] myBooks = new Books[3];

myBooks[0] = new Books();

你在数组中定义一本书。因此,您可以在之后设置标题。


2
投票

当你创建Books[] myBooks = new Books[3]。它会创建一个可以容纳书籍对象的数组,但是所有的值都是null。你没有把任何东西放到那个数组中。虽然访问myBooks [0] .title它实际上是在null值上调用title这样抛出空指针异常。

在第二种情况下,您将分配书籍对象,然后在该对象上调用标题。所以主要的一点是,当你在null对象上调用方法或属性时,它会抛出异常。 myBooks [0] =新书(); myBooks [0] .title ='Book1 title';


1
投票

注释内联以理解它

class TestForBook {

   Books[] myBooks = new Books[3]; // here you have initialized an array of size 3, but it is currently empty, but three Book object can fit in it
   System.out.println('myBooks length is ::' + myBooks.length);//prints 3. Its correct. // since you have specified the length of the array, this will return 3 despite it being empty

  myBooks[0].title = 'Book1 title'; // This throws null pointer exception because your books array is empty, myBooks[0] = null, hence the null pointer exception.

  myBooks[0] = new Books(); //now you have added a book object in the empty book array at index 0
  myBooks[0].title = 'Book1 title'; //since myBooks[0] now contains a books object that your created above, this will return that object instead of null and will work. However if you try this with myBooks[1] that will be null as you still have not put a book object at index 1
}
© www.soinside.com 2019 - 2024. All rights reserved.