本文发表在 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:
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:
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:
Child child =null;
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