☰ Topics

Packages

It is a mechanism to encapsulate a group of classes, interfaces and sub packages. Many implementations of java use a hierarchical files system to manage source and class files. It is easy to organize class files into packages. It is used to keep the classname space compartmentalised. Package statement defines a namespace in which classes are stored. If you omit the package statement, the class name are put into the default package which has no name. You can create a hierarchy of packages where each package is denoted as package1, package2, package3...and soon. Package hierarchy must be reflected in the file system.
Java has its own some inbuilt packages. Some of them are:- java.lang.*, java.util.*, java.io.*, java.applet.*, java.awt.* etc. Programmers can define their own packages to bundle group of classes/interfaces etc. It is a good practice to group related classes implemented by you. A specific location that the java compiler will consider as the root of any package hierarchy is controlled by CLASSPATH.

Creating a Package
For creating a package, you should choose a name for the package and include a package statement along with that name at the top of every source file that contains the classes/interfaces etc. that you want to include in the package.
Syntax:-

 package package_name;
This statement should be used in the beginning of the program to include that program in that particular package.

For ex:-
 package Mypack;
 class Balance{
    String name;
    double bal;
    Balance(String n,double d){
        name=n;
        bal=b;
    }
    void show(){
        if(bal>150){
            System.out.print("-->");
            System.out.println(name + ": $" + bal);
        }
    }
 }
 class AccountBalance{
    public static void main(String args[]){ 
        Balance current[]=new Balance[3];
        current[0]=new Balance("K.J.FIELDING",123.23);
        current[1]=new Balance("Will Tell",157.09);
        current[2]=new Balance("Tom Jackson",-67.89);
        for(int i=0;i<3;i++){
            current[i].show();
        }
    } 
 } 

Compiling packages in java
The java byte code for all the classes (and interfaces) specified in the source files AccountBalance. Java will be placed in the directory named Mypack.

To compile the classes under Mypack package :- 
    c:\Mypack>javac AccountBalance.java
To run this program:- c:>java Mypack.AccountBalance
OUTPUT:
    
--->Will Tell:$157.09
The import keyword is used to attach package or package files in the program. All the import statement is written above the class.