Last Updated: 15 July, 2023
In Java, the import statement is used to access classes, interfaces, etc. from other packages into the current Java class.
Java provides a feature called "static import" that allows us to access static members (fields and methods) of a class directly into the current Java class. This feature was introduced in Java 5 to provide more convenient access to frequently used static members.
To use static import, we need to use the "static import" statement, followed by the class name and the static member(s) we want to import.
Here's an example:
import static packageName.ClassName.staticMember;
For example, if we do any mathematical calculation using the Math class, we call the Math class methods using the Math class, such as Math.sqrt(), Math.pow(), Math.abs(), etc., but by using static import, we can directly access these methods without using the Math class, such as sqrt(), pow(), abs(), etc.
"static import" improve the code's readability and enhance coding.
Without static import - Calling static methods using class name
Output
Square root of 4: 2.0
Power value of 2, 2:4.0
Absolute value of 6.3:6.3
Using static import - Calling static methods without class name
Output
Square root of 4: 2.0
Power value of 2, 2:4.0
Absolute value of 6.3:6.3
Calling static method from a different package using static import
Class: PrintTodayDate.java
Class: Test.java
Output
Today is: Sun Mar 05 00:15:32 IST 2023
If two static members of the same name are imported from multiple different classes, the compiler will throw an error, as it will not be able to determine which member to use in the absence of class name qualification. For example, the following code will fail to compile:
Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The field MAX_VALUE is ambiguous at com.javabytechie.staticimport.Example3.main(Example3.java:8)
In this case, MAX_VALUE is ambiguous, as the MAX_VALUE field is an attribute of both java.lang.Integer and java.lang.Byte. Prefixing the field with its class name will disambiguate the class from which MAX_VALUE is derived, but doing so makes the use of a static import redundant.
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com
Related Articles