In Go, it is OK to call a method on a null pointer so long as that pointer is never dereferenced:
type empty struct{}
func (e *empty) Allocated() bool { return e != nil }
(For runnable code, click here)
In Java, however, calling a method on a null pointer, even if the method never dereferences any member variables, still causes a null pointer exception:
class Test {
public boolean Allocated() { return this != null; }
}
Does anybody know why this behavior exists? Is there some advantage that it gives? Thoughts?
This is because all Java methods are virtual.
When you write someInstance.Allocated()
, the runtime needs to check whether someInstance
is actually of a derived type that overrides the method.
In theory, this restriction could have been relaxed for final
or private
methods.
I assume that the language designers chose not to for consistency. (and so that removing final
wouldn't be a breaking change)
The answer by SLaks is good from a Java perspective. I don't have a clue about Java but I know Go and here's my answer:
First of all nil
is not the same as a NULL
pointer, there are some fundamental differences.
Then, methods in Go are not part of a type's instance but the type itself i.e. Go does not store the vtable inside objects, like Java does:
var e *empty
fmt.Println(e.Allocated())
is the same as… (syntactic sugar for…):
var e *empty
fmt.Println((*empty).Allocated(e)) // This is valid code
Note how Allocated
is invoked as a member of *empty
, much like a static method in traditional "OOP" languages.
In fact, (*empty).Allocated
is just a function name with a weird notation that includes a dot, an asterisk and parens.
Because the receiver is just another argument, the fact that it is nil
is unimportant to the method dispatch mechanism.
In Go, it is OK to call a method on a null pointer so long as that pointer is never dereferenced
If by OK you mean legal, then it's even OK to call a method on a nil
value and dereferencing it. The compiler won't complain - you'll just get a runtime panic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With