Static import Static import

Static import Static import

  To use static members (methods and variables) we must give the class that provides this static member.

  Using static import can make the static variables and static methods of the imported class directly visible in the current class , and use these static members without giving their class names.

  Static import is also a new feature introduced by JDK5.0. The following examples illustrate the usage of static import:

  

  For example, first define a class like this in a package:

   

copy code
package com.example.learnjava;

public class Common
{

    public static final int AGE = 10;
    public static void output()
    {
        System.out.println("Hello World!");
    }
}
copy code


  When used in another package , without static import, it is used like this:

  

copy code
package com.example.learnjava2;

import com.example.learnjava.Common;

public class StaticImportTest
{
    public static void main(String[] args)
    {
        int a = Common.AGE;
        System.out.println(a);
        
        Common.output();
    }

}
copy code


  The import statement is added in front to import the Common class . When using the static member variables and static methods, you need to add the class name .

 

Use static imports

  The syntax for static import is:

  import static package name. class name. static member variable;

  import static package name. class name. static member function;

  Note that the imported member variables and method names.

  As the previous program uses static import:

copy code
package com.example.learnjava2;

import static com.example.learnjava.Common.AGE;
import static com.example.learnjava.Common.output;

public class StaticImportTest
{
    public static void main(String[] args)
    {
        int a = AGE;
        System.out.println(a);
        
        output();
    }

}
copy code

 

shortcoming

  Excessive use of static imports can reduce the readability of the code to a certain extent.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324616413&siteId=291194637