Can "this" ever be null in Java?

Viewed 25869

Saw this line in a class method and my first reaction was to ridicule the developer that wrote it.. But then, I figured I should make sure I was right first.

public void dataViewActivated(DataViewEvent e) {
    if (this != null)
        // Do some work
}

Will that line ever evaluate to false?

11 Answers

If the method is static, then there isn't any this. If the method is virtual, then this cannot be null, because in order to call the method, the run-time will need to reference the vtable using the this pointer. If the method is not virtual then, yes, it is possible that this is null.

C# and C++ allow non-virtual methods, but in Java all non-static methods are virtual, so this will never be null.

Related