I have class Book
private
Author author;
String title;
int noOfPages;
etc as get/set...
class Book extends class Author
public String nameOfAuthor;
My Question is : Why do I need to initialize
Author author = new Author(); // in private varible of class Book.
I'm wondering why I coded in eclipse
Author author ; // in private varible of class Book.
Eclipse doesn't return any error, but in console it looks like this:
Exception in thread "main" java.lang.NullPointerException
at Book.setAuthorName(HelloWorld.java:25)
at HelloWorld.main(HelloWorld.java:41)
set/get is done. Where is Author's name when I initialize
Author author;
????
A declaration of a field (static or non-static) of a reference type which lacks an initializer is initialized by default with null
.
It's like if you did:
Author author = null;
A local variable without initializer is not initialized by default and will yield a compile time error if it used with no value.
You need to create an object because otherwise variable Author points to nothing or null.
// Declare the variable
Author author;
// Create an object (with the new operator) and assign the object to the variable
author = new Author();
Does this answer your question?
When you create an object this way
Author a;
It is just
Author a = null;`
Null is an "undefined value". How can you for example get name of nothing? Nothing won't tell you "Hi, my name is NOTHING".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.