About NullPoiterException.

system (_)
本文发表在 rolia.net/zh 相约加拿大网上社区枫下论坛
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");
// 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;
//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/zh
2000-9-4 -05:00
This post has been archived. It cannot be replied.
Page address has been copied.
To share, click to copy page address.
Share Online by QR Code

Back To Topic: Java Q&A (2) (compiled by jabber)

Back To Forum: HOME枫下论坛枫下论坛主坛工作学习IT技术讨论