Java provides a mechanism for partitioning the class namespace into more manageable parts. This mechanism is the package. The package is both naming and visibility controlled mechanism. Package can be created by including package as the first statement in java source code. Any classes declared within that file will belong to the specified package. Package defines a namespace in which classes are stored.
The syntax for defining a package is:
package pkg;
Here, pkg is the name of the package
eg : package
mypack;
Packages are mirrored by directories. Java uses file system directories to store packages. The class files of any classes which are declared in a package must be stored in a directory which has same name as package name. The directory must match with the package name exactly. A hierarchy can be created by separating package name and sub package name by a period(.) as pkg1.pkg2.pkg3; which requires a directory structure as pkg1\pkg2\pkg3.
Syntax:
To access package In a Java source file, import statements
occur immediately following the package statement (if
it exists) and before any class definitions.
Syntax:
import pkg1[.pkg2].(classname|*);
Example:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
System.out.println("Volume is:"+(l*b*h));
}
}
Source file:
import package1.Box;
class volume
{
public static void main(String args[])
{
Box b=new Box();
b.display();
}
}