can we call any method on null object?

Anand picture Anand · May 2, 2011 · Viewed 21.1k times · Source

is it possible?

Object obj=null;

obj.someMethod();

someMethod{/*some code here*/}

Answer

Matti Virkkunen picture Matti Virkkunen · May 2, 2011

You can call a static method on a null pointer. The pointer will naturally be completely ignored in a static method call, but it's still a case when something that (without looking at the class definition) seemingly should cause a NullPointerException runs just fine.

class FooObject {
    public static void saySomething() {
        System.out.println("Hi there!");
    }
}

class Main {
    public static void main(String[] args) {
        FooObject foo = null;
        foo.saySomething();
    }
}

But just to make it clear - no, you can't call an instance method with a null pointer. Protecting the programmer against this is one of the really basic protections that set languages like Java apart from "lower level languages" such as C++. It enables the error to be reported at the calling end, instead of it causing an inexplicable segfault/whatnot inside the method itself.