When used like this:
import static com.showboy.Myclass;
public class Anotherclass{}
what's the difference between import static com.showboy.Myclass and import com.showboy.Myclass?
See Documentation
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.
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. If you overuse the static
import feature, it can make your
program unreadable and unmaintainable,
polluting its namespace with all the
static members you import. Readers of
your code (including you, a few months
after you wrote it) will not know
which class a static member comes
from. Importing all of the static
members from a class can be
particularly harmful to readability;
if you need only one or two members,
import them individually. Used
appropriately, static import can make
your program more readable, by
removing the boilerplate of repetition
of class names.
There is no difference between those two imports you state. You can, however, use the static import to allow unqualified access to static members of other classes. Where I used to have to do this:
import org.apache.commons.lang.StringUtils;
.
.
.
if (StringUtils.isBlank(aString)) {
.
.
.
I can do this:
import static org.apache.commons.lang.StringUtils.isBlank;
.
.
.
if (isBlank(aString)) {
.
.
.
You can see more in the documentation.
Static import is used to import static fields / method of a class instead of:
package test;
import org.example.Foo;
class A {
B b = Foo.B_INSTANCE;
}
You can write :
package test;
import static org.example.Foo.B_INSTANCE;
class A {
B b = B_INSTANCE;
}
It is useful if you are often used a constant from another class in your code and if the static import is not ambiguous.
Btw, in your example "import static org.example.Myclass;" won't work : import is for class, import static is for static members of a class.
The basic idea of static import is that whenever you are using a static class,a static variable or an enum,you can import them and save yourself from some typing.
I will elaborate my point with example.
import java.lang.Math;
class WithoutStaticImports {
public static void main(String [] args) {
System.out.println("round " + Math.round(1032.897));
System.out.println("min " + Math.min(60,102));
}
}
Same code, with static imports:
import static java.lang.System.out;
import static java.lang.Math.*;
class WithStaticImports {
public static void main(String [] args) {
out.println("round " + round(1032.897));
out.println("min " + min(60,102));
}
}
Note: static import can make your code confusing to read.
the difference between "import static com.showboy.Myclass" and "import com.showboy.Myclass"?
The first should generate a compiler error since the static import only works for importing fields or member types. (assuming MyClass is not an inner class or member from showboy)
I think you meant
import static com.showboy.MyClass.*;
which makes all static fields and members from MyClass available in the actual compilation unit without having to qualify them... as explained above
The import allows the java programmer to access classes of a package without package qualification.
The static import feature allows to access the static members of a class without the class qualification.
The import provides accessibility to classes and interface whereas static import provides accessibility to static members of the class.
Example :
With import
import java.lang.System.*;
class StaticImportExample{
public static void main(String args[]){
System.out.println("Hello");
System.out.println("Java");
}
}
With static import
import static java.lang.System.*;
class StaticImportExample{
public static void main(String args[]){
out.println("Hello");//Now no need of System.out
out.println("Java");
}
}
See also : What is static import in Java 5
Say you have static fields and methods inside a class called MyClass inside a package called myPackage and you want to access them directly by typing myStaticField or myStaticMethod without typing each time MyClass.myStaticField or MyClass.myStaticMethod.
Note : you need to do an
import myPackage.MyClass or myPackage.*
for accessing the other resources
The static modifier after import is for retrieving/using static fields of a class. One area in which I use import static is for retrieving constants from a class.
We can also apply import static on static methods. Make sure to type import static because static import is wrong.
What is static import in Java - JavaRevisited - A very good resource to know more about import static.
Related
This question already has answers here:
Calling static method from another java class
(3 answers)
Closed 1 year ago.
In java, I know I can use methods from other class by creating that class in my main myClass newClass = new myClass() and then use methods by doing myClass.myMethod(), where myMethod() is defined in myClass.java, but what if I want a file named utils.java that contains a bunch of useful methods, I just want to use a function that there's in this file, is this possible? How can I import and use the functions from that file?
You do not need to "import" the functions, you would need just to create a class that keeps all your needed functions, and import that class.
I am supposing you use an IDE, you could go to your IDE and create a simple class.
e.g:
public class Utils
{
public static int doSmth(/* Your parameters here */)
{
// Your code here
}
public static void yetAnotherFunction(/* Your parameters here */)
{
// Your code here
}
}
The most important keyword here is static, to understand it I suggest you check my answer here: when to decide use static functions at java
Then you import this class to any of your other classes and call the static functions, without creating an Object.
import package.Utils;
public class MainClass
{
public static void main(String[] args)
{
Utils.doSmth();
}
}
You can add at the beginning:
import
like-
import utils;
Assuming it is in the same package as the current class
Else it should be:
import <package name>.<class name>
Yes, you can import methods but there are caveats. The methods are defined on a class. The methods are defined as static. The import employs the keyword static. Keep in mind that importing methods directly can create confusion and complicate debugging. Consider importing the class and invoke the method from the class. When/whether defining a utility class makes sense and how to implement them are separate discussions.
package some.path;
public class MyUtils {
public static int add(int x, int y) { return x + y; }
}
To import the method
package some.other.path;
import static some.path.MyUtils.add; // note keyword static here
public class MyClass {
private int a, b;
public int sum() { return add(a,b); }
}
Or, import the class and use the method statically
package some.other.path;
import some.path.MyUtils;
public class MyClass {
private int a,b;
public int sum() { return MyUtils.add(a,b); }
}
I know that the traditional import statement is for classes and the import static statement is for static members. But what should you use for static nested classes?
Consider:
public class MyUtilityClass {
public static class SomeNestedClass {
//...
}
public static class AnotherNestedClass {
//...
}
}
With usage:
import MyUtilityClass.AnotherNestedClass;
import static MyUtilityClass.SomeNestedClass;
public class Main {
public static void main(String[] args) {
SomeNestedClass a = new SomeNestedClass();
AnotherNestedClass b = new AnotherNestedClass();
}
}
You see, both import and import static statements can be used. But which one is more correct, or more typical, or recommended by most coding guidelines?
As general best practice, static import should be used for Members, and import for Classes.
From the java documentation for static import:
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.
If we use static import for a class, will the compiler generate a class file for statically imported class when compiling the actual class?
Ex:
import static com.x.y.util.B.getIds();
public class A {
...
}
When compiler compiles class A, will it generate class files for B as well?
When you use some type in class using key word import or just by full name to it. You must assure that during compilation time, compiler has that both classes in build path.
The static import allow you to access static members of imported class. Nothing more.
class Bar {
public static int getID() {
return -1;
}
}
And for static import
import static Bar.getID;
class Foo {
private void foo() {
int id = getID(); //instead of Bar.getID();
}
}
Read more on Oracle docs
No, import statement does not cause compiler to generate anything. Think about it: how can compiler generate class if it does not have a source code? Compiler by definition translate source code into executable code (or byte code in case of java).
BTW the syntax of static import in your example is not correct. You should not use () in static import:
import static com.x.y.util.B.getIds;
This question already has an answer here:
static member in Java
(1 answer)
Closed 8 years ago.
package pack1;
public class A {
public static int i = 10;
public static void test() {
System.out.println("done");
}
}
This is separate .class file:
package pack2;
import pack1.A.*;
public class Manager0 {
public static void main(String args [] ) {
System.out.println(A.i);
A.test();
}
}
When I run Manager0 class it shows error because I used import pack1.A.*; instead of import pack1.A;, but why doesn't import pack1.A.*; work? I mean doesn't import pack1.A.*; mean import everything in class A?
You're looking for static imports. That should be:
import static pack1.A.*;
.. and you should really avoid it, specially using like that. If you want a specific member, import it specifically by using it's name.
It failed without static because you can't import members of a class non-statically. You can only use so called Import-on-demand, to import classes from a particular packages, or static import-on-demand to import static members of a class.
I am currently working on understanding how to import other classes from a certain package in Java to another package and that certain class.
I was wondering how would I import a method from a certain class in Java to another one since I obviously can't "extend" that class to gain that method since its in some other package.
Example:
package Responses;
public class Hello {
public static void sayHello() {
System.out.print("HELLO!");
}
}
The question:
How do you import sayHello from the Hello class that's in package Responses.
package Start;
public class Begin {
public static void main(String[] args) {
sayHello();
}
}
I am not extending any classes like I stated above, so please don't suggest that.
Import the class that the function resides in:
import Responses.Hello;
Then you can call the function: Hello.sayHello();
In Java there is no construct to directly import a method, but you can import the class in which it resides.
import static Responses.Hello.sayHello;
Then in your other class you can do:
sayHello();
Note: You can only import methods if they are static.
You either import whole classes (A) or their static members (B).
A:
import responses.Hello;
public class Begin {
String myString = Hello.sayHello();
}
B:
import static responses.Hello.sayHello; // To import all static members use responses.Hello.*;
public class Begin {
String myString = sayHello();
}
What oracle says about the usage of static imports:
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. If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually. Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.
Find the whole thing here.
PS
Please use naming convention for your packages:
Package names are written in all lower case to avoid conflict with the names of classes or interfaces.
That's from here
One way is to make your sayHello() method public static. Like
public class Hello {
public static void sayHello() {
System.out.print("HELLO!");
}
}
Then in your Begin class, you can call sayHello using Hello. Of course you should import that Hello class first if they are not under the same package.
public static void main(String[] args) {
Hello.sayHello();
}