Ads

Tuesday, 31 October 2017

What is Package? How can we create our own package?

 Package

→ "Package is a group of similar types of classes, interfaces, and sub packages".

Java can be categorized in 2 forms:

  #1. Built-in Package
  #2. User-defined Package

 

There are many built-in packages such as java.lang, java.swt, java.io etc.
 

The package is the very important concept of java.

Simply saying a package is just a container or collection of classes. So, it is a directory or folder which contains the source files and it's class files.
 

To Create a package, package keyword is used as the first statement of your program. After, package keyword you have to give the package name. In this package i.e. directory, your class files and source file will be stored. And if you do not specify and package as we did earlier, the file will be stored in the default package. But it is good to define a package for your classes.
 

Following is the syntax to define a package.

         package <packagename>
 

Here, your class file must be in the directory named as the package name.
The simple example of a package

The package keyword is used to create a package in java.
 
//save as Simple.java 
package mypack; 
public class Simple

    public static void main(String args[])
    { 
         System.out.println("Welcome to TheJavaXpert");  
    } 
}


How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

javac -d directory java filename

Example

javac -d. Simple.java 

How to run package program


You need to use the fully qualified name:

Compile: javac mypack.Simple

Run : java mypack.Simple
 

Advantages Of  Package


1. They can be easily maintained.

2. Java package provides access protection.

3. Java package removes collision.
Post a Comment

Click Here