A Java package is a mechanism for organizing Java classes. Package are used in Java, in-order to avoid name conflicts and to control access of class, interface and enumeration etc.
A package can be defined as a group of similar types of classes, interface, enumeration and sub-packages.
We can define package using package keyword.
java.lang
, java.util
etc.Creating a package in java is quite easy. Simply include a package command followed by name of the package as the first statement in java source file.
There can be only one package statement in each source file.
If package statement not used in source file than it takes default package for all classes, interfaces and enumeration.
package firstpack; public class Test{ public static void main(String args[]){ System.out.println("Testing package"); } }
To run this program:
Package is a way to organize files in Java, it is used when project consist multiple modules. Package's access level also allows you to protect data from being used by the non-authorized classes.
import keyword is used to import built-in and user defined packages into your java source files. If a class wants to use another class in the same package, the package name does not need to be used. Classes in to the same package use without any import statement.
Import statement is kept after package statement.
There are three ways to refer that is present in different package.
1) Using fully qualified name
class Test extends java.util.Date{ //statements }
2) import the class you want to use :
import java.util.Date; class Test extends Date{ //statements }
3) import all the classes from the particular package:
import java.util.*; class Test extends Date{ //statements }
static import is a feature that expands the capabilities of import keyword.
It is used to import static member of a class. We all know that static member are referred in association with its class name outside the class. Using static import, it is possible to refer to the static member directly without its class name.
There are two general form of static import statement.
import static package.class-name.static-member-name;
import static java.lang.Math.sqrt; //importing static method sqrt of Math class
import static package.class-type-name.*;
import static java.lang.Math.*; //importing all static member of Math class
public class Test { public static void main(String[] args) { System.out.println(Math.sqrt(144)); } }
12
import static java.lang.Math.*; public class Test { public static void main(String[] args) { System.out.println(sqrt(144)); } }
12