Pregunta

Consider the following class

public final class Constant {
  public static final String USER_NAME="user1";
  //more constant here
}

This class in the package B.

Now I am going to use this in package A. Consider following two ways which can use.

Method 1- use import B.Constant

import B.Constant;

public class ValidateUser {
public static void main(String[] args) {
   if(Constant.USER_NAME.equals("user1")){

   }
  }
 }

Method 2- use import static B.Constant.USER_NAME;

import static B.Constant.USER_NAME;

public class ValidateUser {
public static void main(String[] args) {
   if(USER_NAME.equals("user1")){

   }
 }
}

My question is is there any difference or advantage normal import over static import in this case?

¿Fue útil?

Solución

The only difference between a normal import and an import static is that the latter is for moving static members of some other class or interface — especially constants — into scope. It's up to you whether you use it; I like it because it keeps the body of the class shorter, but YMMV.

There are no performance benefits or penalties to using them (except possibly when compiling, as if you care about that) as they compile into identical bytecode.

Otros consejos

The main difference is Readablity, Constant.USER_NAME is less readable when compared to USER_NAME.

From Documentation:

Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.

But in any case, try to avoid doing

import static B.Constant.*;

because it can pollute its namespace with all the static members you import.

I use static imports very rarely and only where they actually make the code a little easier to follow.

According to oracle:

http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html

So when should you use static import? Very sparingly! Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent access to static members from one or two classes. If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually. Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.

The important points to note here:

  • Use it when you require frequent access to static members from one or two classes
  • Used appropriately, static import can make your program more readable

And commenter @Donal Fellows, says appropriately that using an IDE to manage static imports is less risky. I agree as modern IDE's have come a long way and will take out a lot of the pains of managing dependancies and tracing method calls back to a parent.

For example all methods in Math class are static an we call all of them as Math.mathod().But if we import math class like this : import static java.lang.Math.*; We don't have to add Math before the method :

import static java.lang.Math.*;

public class Program {

    public static void main(String args[]) {

        System.out.println(sqrt(25));
        System.out.println(log(100));
        System.out.println(PI);
    }
}

Static imports let you avoid qualifying static members with class names.

Once the static member is imported then you can use it in your code without the class name prefix.

Good example:

import static sample.SampleStaticValues.NUM_ZERO;
…

enum OddEven {odd,even}


//need not do SampleConstants.NUM_ZERO due to static import feature
if(num % 2 == NUM_ZERO){
   System.out.println("The num " + num + " is: " + OddEven.even);
}

  package sample;
  public class SampleStaticValues {
  public static int NUM_ZERO = 0;
  public static int NUM_ONE = 0;
}

Static imports are used to save your time and typing. If you hate to type same thing again and again then you may find such imports interesting.

The import allows the java programmer to access classes of a package without package qualification.

The static import feature allows to access the static members of a class without the class qualification.

Lets understand this with the help of below examples:

Example 1: Without Static Imports

class Demo1{
   public static void main(String args[])
   {
      double var1= Math.sqrt(5.0);
      double var2= Math.tan(30);
      System.out.println("Square of 5 is:"+ var1);
      System.out.println("Tan of 30 is:"+ var2);
   }
}

Output:

Square of 5 is:2.23606797749979
Tan of 30 is:-6.405331196646276

Example 2: Using Static Imports

import static java.lang.System.out;
import static java.lang.Math.*;
class Demo2{
   public static void main(String args[])
   {
      //instead of Math.sqrt need to use only sqrt
      double var1= sqrt(5.0);
      //instead of Math.tan need to use only tan
      double var2= tan(30);
      //need not to use System in both the below statements
      out.println("Square of 5 is:"+var1);
      out.println("Tan of 30 is:"+var2);
   }
}

Output:

Square of 5 is:2.23606797749979
Tan of 30 is:-6.405331196646276

In order to access static members, it is necessary to qualify references with the class they came from. For example, one must say:

double r = Math.cos(Math.PI * theta);
or
System.out.println("Blah blah blah");

You may want to avoid unnecessary use of static class members like Math. and System. For this use static import. For example above code when changed using static import is changed to:

import static java.lang.System.out;
import static java.lang.Math.PI;
import static java.lang.Math.cos;
...
double r = cos(PI * theta);
out.println("Blah blah blah");
...

So whats the advantage of using above technique? Only advantage that I see is readability of the code. Instead of writing name of static class, one can directly write the method or member variable name. Also keep one thing in mind here. Ambiguous static import is not allowed. i.e. if you have imported java.lang.Math.PI and you want to import mypackage.Someclass.PI, the compiler will throw an error. Thus you can import only one member PI.

Guys today we came across a big disadvantage of static imports. Just sharing it below.

  1. XXXConsts.java had EVENT_ID (EVENT_ID = "EVENT_ID") which was statically imported in a class XXXComceteImpl.java that extends from AbstractService.java
  2. XXXZeloImpl.java that extends from AbstractService.java wanted EVENT_ID = "eventId". So EVENT_ID = "eventId" was declared in AbstractService.java.
  3. Now #1 was broken as the EVENT_ID in XXXComceteImpl.java was referring to EVENT_ID in AbstractService.java
  4. May be the naming of EVENT_ID = "eventId" should have been different.
  5. Note :- Naming of the classed are redacted version so it looks unusual.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top