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");
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/zh
(#8036@0)
2000-9-4 -05:00

回到话题: Java Q&A (2) (compiled by jabber)

回到论坛: HOME枫下论坛枫下论坛主坛工作学习IT技术讨论

URL:   
http://www.rolia.net/zh/post.php?f=0&p=8036