If Java does not have a preprocessor, what is import?

5 answers

Import, although the name does not "import" anything, it just allows you to call classes without a full name.

To clarify if I do import java.util.ArrayList; , now I can refer to the ArrayList class as an ArrayList . If I do not, I can still use the class, I just need to call it java.util.ArrayList .

If you import entire packages using * , the worst thing that can happen is a name collision, so you should use the full name to refer to the Java class, but it does not use more memory at runtime.

Classes in java.lang automatically "imported".

Java 1.5 introduces static imports , which allows programmers to refer to imported static members as if they were declared in a class that uses them. They should be used sparingly. Acceptable use is importing JUnit Assert methods. For example, with traditional imports:

 import org.junit.Assert; ... Assert.assertEquals(expected, actual); 

With static import:

 import static org.junit.Assert.assertEquals; ... assertEquals(expected, actual); 
+13
source

Import allows you to use an unqualified class name. For example, with import java.util.ArrayList you can use an unqualified name of type ArrayList in your code. Without an import statement, you should always use the full name: java.util.ArrayList .

There is also a static import that puts static class members in the namespace of the compilation unit.

+2
source

import makes package names known in the file where it is used. This is not at all comparable to C #inlclude .

+1
source

Due to the tight source code naming convention, the Java compiler can easily find the appropriate source or class files only from the full name of the package and class. By a fully qualified name, I mean specifying the complete package and class, for example.

 java.util.ArrayList x = new java.util.ArrayList (); 

An alternative to this long coding style is to use import statements.

 import java.io.*; import java.util.ArrayList; ArrayList x = new java.util.ArrayList(); 

It is also a great help for understanding elses user code.

+1
source

A way to tell the compiler that you are using a class from another package?

EDIT: specification link

0
source

Source: https://habr.com/ru/post/901415/


All Articles