Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java "static import" vs. "import static" in Java 8

I was trying to use use static imports on Java, but I was writing it wrong

static import java.lang.System.out;

And the code compiled (although the "out" symbol couldn't be found), no syntax errors.

So, what does the "static import" actually means?

like image 579
paulotorrens Avatar asked Jan 19 '13 02:01

paulotorrens


People also ask

Is it good to use static import in Java?

So when should you use static import? Very sparingly! Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent access to static members from one or two classes.

Is static import bad in Java?

by Joshua Bloch.) This is considered bad Java programming practice because when a class implements an interface, it becomes part of the class's public API. Implementation details, such as using the static members of another class, should not leak into public APIs.

What does import static mean in Java?

Static import is a feature introduced in the Java programming language that allows members (fields and methods) which have been scoped within their container class as public static , to be used in Java code without specifying the class in which the field has been defined.

Which is the true about the static import statement in Java?

Explanation: The static import feature of Java 5 facilitate the java programmer to access any static member of a class directly. There is no need to qualify it by the class name.


1 Answers

This should not compile.

static import java.lang.System.out;

According to the JLS, a single static import should look like this:

import static java.lang.System.out;

All forms of the Java import statement start with the import keyword, and I don't think there is any other context (i.e. apart from an import statement) in which the import keyword can be used.

Note: the import and static keywords are not modifiers in this context, so the "modifiers can be supplied in any order" meta-rule does not apply here.


In short, either your compiler / IDE is broken or confused ... or what you are looking at is not real Java source code.

like image 162
Stephen C Avatar answered Oct 05 '22 18:10

Stephen C