开发者

What does this mean Calling the instance method of a null object " [duplicate]

开发者 https://www.devze.com 2023-02-08 19:15 出处:网络
This question already has answers here: What is a NullPointerException, and how do I fix it? (12 answers)
This question already has answers here: What is a NullPointerException, and how do I fix it? (12 answers) Closed 5 years ago.

My program is throwing a NullPointerException. I suspect Calling the instance method of a null object is the reason for it throwing a null pointer e开发者_开发问答xception.

Can anyone explain what does this actually mean?


It means you have code that looks like this:

foo.method();

...and foo is null. foo has to refer to an object instance in order for you to call methods or access fields on it. E.g., you must assign something to foo (something other than null) like foo = new Foo(); or such.


There are two types of methods in Java: static and instance. A static method can be invoked WITHOUT an instance of the class, an instance method MUST be invoked on an instance of the class. Static methods cannot invoke instance methods or use instance data, but the reverse is not true — instance methods can invoke static methods and use static data.

The null pointer exception (NPE) you're seeing is because you're invoking an instance method on a null reference. You need to set the reference to an actual object of that class (or a subclass of it).

Interestingly enough, though, it's quite legal to invoke a static method on a null reference. It's very odd syntax and somewhat misleading, but it will work.


You called a method on an object which you did not initialize. For exemple your code has a line such as :

myObject.callMethod();

But this "myObject" has not been initialized with a line like :

myObject = new myObjectClass();

Please post some code if you want a more in-context answer !

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号