How to use static import in Java?


By using static import statement such as importing; Math class

import static java.lang.Math.*;

All of the fields and methods of Math class will be available inside the importer class without having a reference to Math class. (Math.PI)

Let me give you an example;

package staticimportexample;

import static java.awt.Color.*;
import static java.lang.Math.*;
import static java.lang.System.*;

/**
* @author tunatore
*/
public class Main {

/**
* import static example
*/

public static void main(String[] args) {

// by importing with static keyword
// instead of accessing methods or fields by the class name reference
// such as Math.PI or Color.GREEN
// these fields can be used like PI or GREEN in the code
// example:

//orginal access must be Math.PI
//using static import gives an access by field name only
System.out.println(“PI –> ” + PI);

//original access must be Math.E
System.out.println(“E –> ” + E);

//original access must be Color.GREEN
System.out.println(GREEN);

//original method Math.sqrt(400)
//after static import
System.out.println(“sqrt(400) –> ” + sqrt(400));

//original System.out.println();
out.println(“I am System.out.println method”);

}

}

Output of the program;

run:
PI –> 3.141592653589793
E –> 2.718281828459045
java.awt.Color[r=0,g=255,b=0]
sqrt(400) –> 20.0
I am System.out.println method
BUILD SUCCESSFUL (total time: 1 second)

Download Source

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s