Java Import Keyword Example
In this example, we will learn about the Java Import keyword. We will talk about Java packages and their types and what problems an import keyword solves when programming in Java.
You may skip the packages section and jump directly to the Import keyword section below.
1. Packages
A java package is used to group related types(classes, interfaces, enumerations, and annotations) and provides access protection and namespace management. Such related types that are part of a package are known as the package members. Throughout this example, we will be often using the term package members to refer to such related types.
There are two types of packages in Java. The built-in packages and the user-defined or custom packages. Let us discuss each of them.
1.1 Built-in packages
The fundamental classes of the Java Platform have been packaged in java.lang, the classes for (input and output) in java.io, and so on. These are called built-in packages.
Java compiler automatically imports two packages for us.
1. The built-in package java.lang
2. The current package (the package for the current file).
1.2 User-defined packages
You can create your own package, give it a valid name and bundle together the classes, interfaces, and other package members created by you inside it. Such a package is termed a user-defined package or a custom package.
For more details on packages check this detailed example on packages.
2. Using Package Members
A package member can be used from outside its package in a class or an interface in one of the following ways:
- Using its fully qualified name.
- Using the import keyword to import a single member of the package.
- Using the import keyword to import all members of the package.
Depending on the situation and need, you can use any of the above techniques. Let’s discuss each in detail with a few examples.
2.1 Fully qualified name
Scenario: Infrequent use of a package member.
To use a member from a different package its fully qualified name(containing the package name) may be used.
In the below example we have a class with the name India declared in the org.adee.samples.country package.
India.java
// India.java package org.adee.samples.country; public class India { }
You can use the fully qualified name of class India with its package name and create a new instance in another class named Info in package org.adee.samples.info. See the example below.
Info.java
// Info.java package org.adee.samples.info; public class Info { // Use class India with its fully qualified name org.adee.samples.country.India india = new org.adee.samples.country.India(); }
Cons: This approach cannot be used when a package member is used frequently because of the following reasons :
- Typing the fully qualified name repeatedly can be annoying.
- The final code using this approach becomes difficult to read.
2.2 What is import keyword ?
The import is a java keyword that is used to make the classes, interfaces, and other members of another package accessible to the current package. The following sections describe the usage of the import keyword.
2.3 Import a single member from a package
Scenario: To use just a few members from the package.
To import a specific class or an interface type into the current package, use the import statement after the package statement(members in default packages have no package statement) and before any type(class, interface, etc.) definitions.
For instance a package org.adee.samples.country has multiple classes and few interfaces defined and you want to use only a single class named Spain, leverage the import keyword, and refer to the Spain class by its simple name. See the example below.
Info.java
//Info.java package org.adee.samples.info; // import statement import org.adee.samples.country.Spain; public class Info { // use class Spain with simple name Spain s = new Spain(); }
Cons: This approach should not be used when most of the members of a package need to be imported in another package as the resulting class will have numerous import statements making the java class file too large.
2.4 Import all the members from a package
Scenario: To use multiple members from a package.
Using the import keyword with the asterisk (*) wild card character after the package name makes all the types(classes, interfaces, enumerations, and annotations) of this package accessible(considering the members are defined with correct access modifiers).
ImportAll.java
// ImportAll.java package org.adee.samples.info; //import statement with (*) wild card import org.adee.samples.country.*; public class ImportAll { //use all class types with their simple name. Spain s = new Spain(); India a = new India(); Greece g = new Greece(); Cannada c = new Cannada(); }
As illustrated above, you can now refer to any class or interface in the org.adee.samples.country package by its simple name.
2.4.1 Misuse of the import keyword
- The import statement cannot be used to match a subset of the members within a package. This will result in a compile-time error.
Invalid import
// this will not work import org.adee.samples.country.S*;
- Another invalid use of an import statement is to use multiple (*) wild card characters in a single import statement.
Invalid import
// The following is an invalid import import org.adee.*.*;
- Another assumption that packages are hierarchical is totally wrong. They appear to be hierarchical but they are not. For example, the Logger class is defined in the java.util.logging package and List interface is defined in the java.util package. It is wrong to assume that the Logger class will be imported by using the import statement import.java.util.*.
WrongUsage.java
// WrongUsage.java package org.adee.samples.info; import java.util.*; public class WrongUsage { // list is visible private List list; // compile time error // Logger cannot be resolved to a type // use import java.util.logging.* private Logger logger; }
To import the Logger class, you may choose to use one of the below import statements.
import java.util.logging.*; import java.util.logging.Logger;
2.5 Importing public nested classes
You can also use the import statement to import the public nested classes of an enclosing class. For more details on nested classes, check this example.
In the following example, City is a public nested class inside an enclosing class Greece.
Greece.java
// Greece.java package org.adee.samples.country; public class Greece { // nested public class City public class City { } }
The import statement in the below examples is used to import the nested class City.
Info.java
// Info.java package org.adee.samples.info; // import class Greece import org.adee.samples.country.Greece; // import nested public classes of Greece; in this case class City import org.adee.samples.country.Greece.*; public class Info { Greece g = new Greece(); City city = g.new City(); }
Note: Using only the statement import org.adee.samples.country.Greece.* will not import the class Greece. Both the imports have to be written explicitly.
2.6 Static Imports
While programming in java, there might be scenarios where you need to access static methods and static (final) constants quite often. One way is to prefix the name of these classes in every usage of such a method or a constant however this might result in a cluttered code.
The static import statement solves this problem and helps to import static methods and static constants to be used without having to prefix the class name every time. See the below illustrations.
StaticUtils.java
// StaticUtils.java package org.adee.samples.staticImports; public class StaticUtils { public static final String TYPE = "sample"; public static void printType() { System.out.println("This is a sample static method in java"); } }
The above class defines a static constant named TYPE and a static method named printType().
ExampleStaticImport.java
//ExampleStaticImport.java package org.adee.samples.info; // static imports import static org.adee.samples.staticImports.StaticUtils.TYPE; import static org.adee.samples.staticImports.StaticUtils.printType; public class ExampleStaticImport { public static void main(String[] args) { System.out.println(TYPE); printType(); } }
In the above code, we have leveraged the static import statement to use the static constants and methods without prefixing the class name.
3. Name Ambiguities
If two separate packages have members that share the same name it is advisable to refer to each member by its qualified name to avoid any name ambiguities. See the example below where a class List is defined in the package org.adee.samples.ambiguity.
List.java
// List.java package org.adee.samples.ambiguity; public class List { }
The package java.util also defines an interface named List that shares the name with the class defined above. To remove any name ambiguity we are referring to each List type by its fully qualified name as shown below.
NameAmbiguity.java
// NameAmbiguity.java package org.adee.samples.ambiguity; public class NameAmbiguity { private org.adee.samples.ambiguity.List myList; private java.util.List javaList; }
4. Download the source code
This was an example of the Java import keyword.
You can download the full source code of this example here: Java Import Keyword Example