×

Loading...

About NullPoiterException.

本文发表在 rolia.net 枫下论坛Q: Jabber, I frequently get a NullPoiterException but I did not understand why. Can you say something about it?

A: Yes. Let me first give you an example in the real life. John and Mary decided to have a baby next year. And they have decided to give it a name "Mark" if it turns out to be a boy. We know a baby can smill and cry. Because Mary is so eager to have a baby, she often says:

Mark, smile!
Mark, smile!
Mark, smile!

Let me ask you a stupid question: As Mary says "Mark, smile!", will "that baby" smile???

No! The reason is that the baby have not yet been borne. This is exactly a NullPoiterException---Mark is not related to some concrete, existing baby. Before the baby is born, you cannot ask it smile.

In Java, programmers uaually first declare a varable name, then create an object instance using "new", next assign this instance to the variable. After that, you can call mathods through variable name. This sounds like:

//other code
Child child= new Child("Mark");
child.smile();
// other code, we assume we have a class Child defined somewhere else

The above cold is OK. However, the following code will throw NullPointerExpecetion:

//other code
Child child =null;
child.smile();
//other code

The reason is that you just hold a variable name "child" for the futire use and have not yet
related to any existing Child.更多精彩文章及讨论,请光临枫下论坛 rolia.net
Sign in and Reply Report

Replies, comments and Discussions: