Types of Import statement in Java

By YuwebDesign

What is import?

Imports are a mechanism for accessing classes inside a package.

Regular Import

A class can have only one package declaration but it can have more than one package import statements.

A package name should be included in the import statement.

package abcpackage; //single package declaration
import xyzpackage;
import anotherpackage;
import anything;

  1. All the classes and interfaces of this package will be accessible but not subpackages.
    import package.*;

    E.g., import all the classes from util package contained inside java.
    import java.util.*;

  2. Only mentioned class of this package will be accessible.
    import package.classname;

    E.g., import Vector class from util package contained inside java.
    import java.util.vector;

    Class name is generally used to avoid conflict
    when two packages have same class name.
    import java.util.Date;
    import my.packag.Date;

Static Import

Static import is a feature introduced in Java (ver. 5+)
that allows members (fields and methods)
defined in a class as public static
to be used in Java code
without specifying the class
in which the field is defined.

You can use fully qualified name (package_name.class_name) to avoid the import statement.

Regular import:

//Declaring a package
package somepackage;
//importing a package
import letmecalculate.Calculator;
public class Demo{
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));

Static import:

//Declaring a package
package anotherpackage;
public class Example{
public static void main(String args[]){
//Using fully qualified name instead of import
letmecalculate.Calculator obj =
new letmecalculate.Calculator();
System.out.println(obj.add(100, 200));

Leave a Reply or Comment

Your email address will not be published. Required fields are marked *