A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations ) providing access protection and namespace management.

Some of the existing packages in Java are −

    java.lang − bundles the fundamental classes

    java.io − classes for input , output functions are bundled in this package

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 so that a programmer can easily determine that the classes, interfaces, enumerations, and annotations are related.


Creating a Package

While 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, enumerations, and annotation types that you want to include in the package.

The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.

Run file -    javac destination_folder \ file_name.java

                       java package_name . class_name


Example -

class A{

void display(){

System.out.print("display");

}

}

class B{

public static void main(String []arr){

A obj=new A();

obj.display();

}

}

Output -

        display


Outside Package Acees

Example -

package p2;

import p.C;

class R{

public static void main(String []arr){

C obj=new C();

obj.display();

}

}

Output -

        display


Example -

package p2;

class A{

public static void main(String []arr){

p.C obj=new p.C();

obj.display();

}

}

Output -

        display show


Example -

package p2;

class B extends p.C{

public static void main(String []arr){

B obj=new B();

obj.display();

}

}

Output -

        display show


Package With in Package

Save file -    folder_name (p) \  A.java

                         folder_name (p) \ folder_name (d) \ S.java


Run file -    javac p \ d \ S.java

                       java p.d.S


Example -

package p;

public class A{

public void display(){

System.out.print("display");

}

}


package p.d;

import p.C;

class S{

public static void main(String []arr){

C obj=new C();

obj.display();

}

}

Output -

        display