Sam Howard Sam is a developer at IDRsolutions who specialises in font rendering and conversion. He's also enjoyed working with SVG, Java 3D, Java FX and Swing.

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?

Did you know...

IDRsolutions offers a whole range of online file converters to convert PDF and Microsoft Excel, Word and Office Documents to HTML5, SVG or image formats?

It is free to use for single file conversions and also includes Developer links if you want to use our commercial software for bulk conversions. Find out more on this page

Sam Howard Sam is a developer at IDRsolutions who specialises in font rendering and conversion. He's also enjoyed working with SVG, Java 3D, Java FX and Swing.

Leave a Reply

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

IDRsolutions Ltd 2020. All rights reserved.