What is the reason of NullPointerException
in a code like that:
TestClass t = null;
t.SomeMethod();
If SomeMethod is an instance method it'll do something with standard
this reference:
public void SomeMethod() {
// Here we'll have a NullPointerException (since "this" is null)
this.SomeField = ... // <- We usually omit "this" in such a code
}
Since this is null we'll have NullPointerException. If method, field etc.
is static it's guaranteed the absense of this reference, so there'll be
no NullPointerException
public static void SomeStaticMethod() {
// You can't put "this.SomeField = ..." here, because the method is static
// Ans since you can't address "this", there's no reason for NullPointerException
...
}
...
TestClass t = null;
// Equal to "TestClass.SomeStaticMethod();"
t.SomeStaticMethod(); // <- "this" is null, but it's not addressed