Sam Howard Sam is a developer at IDRsolutions who mostly specialises in font support and conversion. He's also enjoyed working with Java 3D, Java FX and Swing. His other interests include music and game design.

Java and Static Imports

1 min read

One thing that was mysteriously absent from my Java education was static imports – probably because they’ve been controversial ever since first being introduced way back in J2SE 5.

In case I’m not the only one who missed the whole thing, static imports let you access static fields or methods without needing to qualify them with the name of the class. The classic example of this is statically importing Java’s Math class:

import static java.lang.Math.*;

(...)

double area = PI * d;
double c = sqrt((a*a)+(b*b))

You can also be more specific with your import by just importing java.lang.Math.PI, and so on.

Static imports were introduced because a worrying large number of developers were using interfaces to contain constants, and then extending these interfaces to gain quick and easy access to them. This undoubtedly removes a large amount of boilerplate, but also is completely unrelated to the intended purpose of interfaces.

There’s no question in my mind about whether importing these statically is better than implementing an interface full of static members – it absolutely is, as the visibility is not inherited – but many people argue that you should include the class qualifier anyway for clarity’s sake.

Personally, I think sometimes class names can get in the way and make code harder to read, rather than easier. I think the key point is that the meaning of the imported member’s name must be clear in it’s new context – if it is, then the code will end up easier to read, and since all modern IDEs offer quick and convenient ways of navigating straight to a members definition, in this case I really don’t see a problem.

So what do you think about them? Good, the lesser of two evils, or just plain evil?

If you’re a first-time reader, or simply want to be notified when we post new articles and updates, you can keep up to date by social media (TwitterFacebook and Google+) or the Blog RSS.

Sam Howard Sam is a developer at IDRsolutions who mostly specialises in font support and conversion. He's also enjoyed working with Java 3D, Java FX and Swing. His other interests include music and game design.

Leave a Reply

Your email address will not be published. Required fields are marked *