Java - Import-on-Demand Declaration

What is Import-on-Demand Declaration?

An import-on-demand declaration can import multiple types from a package using one import declaration.

Syntax

The syntax for an import-on-demand declaration is

import <package name>.*;

Example

The following import-on-demand declaration imports all types from com.book2s.demo package:

import com.book2s.demo.*;

The declaration

import p1.*;

imports all types from p1 package but not the type from the p1.p2 package, which is a sub-package of p1.

You cannot use multiple asterisks.

import p1.*.*; // A compile-time error

To import both classes C1 and C2, use two import-on-demand declarations.

import p1.*;
import p1.p2.*;

The following code shows how to import Date class from java.util package using import-on-demand declaration.

Demo

import java.util.*;
public class Main {
  public static void main(String[] args) {
    System.out.println(new Date());
  }//  w w w  .  ja  va2s. co  m
}

Result

Related Topic