Static import
Encyclopedia
Static import is a feature introduced in the Java programming language
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

 that allows members (fields and methods) defined in a class as public static to be used in Java code without specifying the class in which the field is defined. This feature was introduced into the language in version 5.0.

The feature provides a typesafe mechanism to include constants
Constant (programming)
In computer programming, a constant is an identifier whose associated value cannot typically be altered by the program during its execution...

 into code without having to reference the class that originally defined the field. It also helps to deprecate the practice of creating a constant interface
Constant interface
In the Java programming language, the constant interface pattern describes the use of an interface solely to define constants, and having classes implement that interface in order to achieve convenient syntactic access to those constants....

: an interface
Interface (computer science)
In the field of computer science, an interface is a tool and concept that refers to a point of interaction between components, and is applicable at the level of both hardware and software...

that only defines constants then writing a class implementing that interface, which is considered an inappropriate use of interfaces.

The mechanism can be used to reference individual members of a class:

import static java.lang.Math.PI;
import static java.lang.Math.pow;

or all the static members of a class:

import static java.lang.Math.*;



For example, this class:

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
System.out.println("Considering a circle with a diameter of 5 cm, it has:");
System.out.println("A circumference of " + (Math.PI * 5) + "cm");
System.out.println("And an area of " + (Math.PI * Math.pow(2.5,2)) + "sq. cm");
}
}

Can be shortened to:

import static java.lang.Math.*;
import static java.lang.System.out;
public class HelloWorld {
public static void main(String[] args) {
out.println("Hello World!");
out.println("Considering a circle with a diameter of 5 cm, it has:");
out.println("A circumference of " + (PI * 5) + "cm");
out.println("And an area of " + (PI * pow(2.5,2)) + "sq. cm");
}
}
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK