Home » java » Java Packages

Java Packages

In java programming, packages is a collection of related classes and each class define number of method. 

The classes define inside the package that are not accessible by code outside that package.   Packages are stored in a hierarchical manner and explicitly imported into a new class definition.

Java packages are classified into two types:-

  1. Java API(Application Programming Interface) packages or Predefined packages or Built-in packages: These packages are defined by the system. Some example of system defined packages are java.lang, java.util, java.io, java.awt, java.applet etc.               The Java 1.3 contains nearly 60 predefined 
  2. User-defined packages: These packages are defined by the user.

Defining as packages: To define a package, place “package” command as the first statement in the source file.

The syntax of packages creation :-

  • The class that is defined in the package must be public. So that is can be accessible by any another of them.
  • Java uses the file system file directories to store packages. We save the program with number.java and compile the package is as javac_d/number.java. Due to this compilation Mypackage directory is automatically created and .class file is stores in that directory.

Once the package creation has completed. Then the package information is including with the help of “import” keyword.  import keyword links the package with our program.

It is place before the class definition:

Java Package
Java Package
  • In this program, package is within x folder and main program is within y folder in c drive.
  • Package name in this program is x.
  • File name and package class name must be same ex: (number.java- source file).

How to compile:

Note: If we want to access all the classes of information then the classes are stored in different files with the same package name.

Sub Packages

In Java, it is possible to create a sub packages for the main packages.

Syntax

                 package  pack1.pack2;  

Where pack1 is the main package and pack2 is the sub package.

Result

Managed by MochaHost - Fast & Easy WordPress Hosting