Static Imports

posted by: veldte 3 April 2011 No Comment

Be aware that this post will likely confuse and anger you, as it doesn’t really follow the Java you’ve been learning… as such, I thought it was an appropriate time to discuss it, as I’ve been rather busy up until now.

Given the simple object

class {
public static void main(String[] args) {

you can print out the Java approximation of PI.

However, if you used the Math clobject repeatedly within a class, why should you bother typing Math.Whatever each and every time? The answer is that you shouldn’t if you’re lazy.

You can instead do this

import static java.lang.Math.*;
class {
public static void main(String[] args) {
System.out.println(cos(PI * theta));
/* etc */

as most (if not all) methods and constants of the Math class are static.

Essentially, with a static import you can use all static members of the import with explicitly qualifying what class it comes from.

Now, to be less evil: use it sparingly. Like seriously, it will lead to bad habits and occasionally difficult-to-read code especially if you have a dozen of them in the same class, but it is just nice to be lazy sometimes, and sometimes, it makes sense. Basically, don’t be an idiot and have fun. Oh, and this will never come up on the AP CS, nor will Ms. Helen Martin likely look too kindly upon its overuse (as a result of the latter, I recommend using it as much as possible and claim you’re utilizing as many language constructs as you can).

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>