为什么我需要在我想要使用它时初始化一个变量类

时间:2015-10-12 08:46:50

标签: java eclipse oop

我有课堂书

private
Author author;
String title;
int noOfPages;
etc as get/set...

class Book扩展了类作者

public String nameOfAuthor;

我的问题是: 为什么我需要初始化

Author author = new Author(); // in private varible of class Book.

我想知道为什么我在eclipse中编码

Author author ; // in private varible of class Book.

Eclipse不会返回任何错误,但在控制台中它看起来像这样:

Exception in thread "main" java.lang.NullPointerException
    at Book.setAuthorName(HelloWorld.java:25)
    at HelloWorld.main(HelloWorld.java:41)

设置/获取完成。初始化时作者姓名在哪里

Author author;

????

3 个答案:

答案 0 :(得分:2)

默认情况下,null初始化缺少初始化程序的引用类型的字段(静态或非静态)声明。

如果你这样做了:

Author author = null;

默认情况下不初始化没有初始化程序的局部变量,如果没有使用值,则会产生编译时错误。

答案 1 :(得分:0)

您需要创建一个对象,因为否则变量Author指向nothing或null。

// Declare the variable
Author author;
// Create an object (with the new operator) and assign the object to the variable
author = new Author();

这会回答你的问题吗?

答案 2 :(得分:0)

以这种方式创建对象时

Author a;

只是

Author a = null;`

Null是“未定义的值”。你怎么能得到什么名字?什么都不会告诉你“嗨,我的名字没什么”。