Joe's Java and Web Jottings

your host


Your Host

Calendar

««Nov 2009»»
SMTWTFS
1234567
891011121314
15161718192021
22232425262728
2930

My Top Tags

               

Java Libs and Tools

My Other Pages

My RSS Feeds








Don't reference statics through instances. Period.

posted Sunday, 22 February 2004
DavidFlanagan.com:The following program does not throw a NullPointerException

public class StaticFieldThroughNull {
public static void main(String[] args) {
Double d = null;
System.out.println(d.MAX_VALUE);
}
}

This really is supposed to work this way.

This is one of those cases where the IDEs have worked pretty hard to make up for shortcomings in the Java compiler. Eclipse will flag that with a yellow caution marker, even though the standard compiler says nothing.

The fact that it does compile and run without a warning now actually indicates an even bigger caution flag to developers to not write code that way. Suppose instead I had

Double d = new DerivedFromDouble(1.1);

so far, not a problem, because MAX_VALUE is "final" among other things. But imagine that it wasn't final, like it might not be in one's own hierarchy (particularly true with static methods). Then d.MAX_VALUE would be questionable. The compiler has to choose whether it'll find Double or DerivedFromDouble, and my guess is that it would find Double and likely introduce a bug if the programmer wasn't aware of that. Static access does not follow the same polymorphic rules that instance access does.

THAT's why its better to reference statics through class references only, and not through instances.




1. a reader left...
Monday, 23 February 2004 3:10 am

I wouldn't say that the compiler "has to choose". The spec is clear about this: access to static members through an instance uses the static (compile-time) type of the instance, not its dynamic, runtime type.

I agree with the general comment that referencing statics through instances is a bad thing to do.

Using static methods and fields without any qualifier within the class in which they are defined is commonplace and okay, of course.

David Flanagan