Imports

Introduction: This tutorial will teach you how to use Imports in Java. What are imports? Imports are very important... see what I did there?... *sigh* Most programming languages, including Java, are very 'lazy' and will only get the information for classes it knows it will need or is directly referenced. So, if we want to use a method from a class which is in a custom package/location or a Java class which is not loaded by default we will need to import that package. Import format? The format for an import is the following: - All imports must be at the very top of the class file that requires the import. - The keyword "import" must be followed by a valid namespace. - To avoid warnings, the import must be used at least once. What is a namespace? A namespace is another name for a directory/path to a class. Normally this will consist of "{package name}.{class name}". Example: For this example we will use a custom class. To create this example we first need to create a new package, in Eclipse right click on the "src" folder and select New > Package. I have named mine "other". Once you have created your new package you want to create a class within the "other" package. Again, right click and go to New > Class, I have named mine "importThis". As stated above; the imports must be at the top of the file, like so;
  1. import other.importThis;
  2. public class Main {
  3. }
The imported class must be precede by the package name. Now we have the class imported we can use the public static functions within the class. First lets create one, here is a script named "output" which will just output "Hey" to the console...
  1. package other;
  2. public class importThis {
  3. public static void output(){
  4. System.out.println("Hey");
  5. }
  6. }
Save the class and go back to your class with the import of "importThis". We can now use the "output" method we just created by referencing the class name followed by the function name, like so;
  1. importThis.output();
Once ran, the program says "Hey" in the output console. Finished!

Add new comment