|
In order to access static members, it is necessary to qualify references with the class they came from. For example, to access the PI member in the Math class we have to use Math.PI as shown below:-
double r = Math. PI *10;
In order to get around this, programmers put static members into an interface and inherit from that interface which is a bad idea. This problem in Java is known as Constant Interface Antipattern. When a class implements an interface, it becomes part of the class's public API. Implementation.
The static import construct allows unqualified access to static members without inheriting from the type containing the static members. Instead, the program imports the members, either individually:
import static java.lang.Math.PI; OR,,
import static java.lang.Math.*;
Once the static members have been imported, they may be used without qualification:
Example:-
Note:-The static import declaration is analogous to the normal import declaration. Where the normal import declaration imports classes from packages, allowing them to be used without package qualification, the static import declaration imports static members from classes, allowing them to be used without class qualification.
package com.visualbuilder;
import static java.lang.Math.*;
public class StaticImport {
public static void main(String[] args) { System.out.println(PI); System.out.println(Math.PI); }
}
Output:-
The following is the output of the above program.
3.141592653589793 3.141592653589793 |