Sunday, 12 August 2012

Simple way to Create Package in Java

 Package in Java

       Package is collection of classes and interfaces.
       this is the way of grouping classes and interfaces into the single directory.

How to use package ?

    In Java, lots of predefined packages are implemented.like java.util , java.io ,java.awt etc.Use an import keyword when we have to use these packages  functionality.

How to use import Keyword ? When to use import keyword ?

       these are the two basic question ,use import keyword as shown below:

 import java.NameOf Package;

               for example ,lets consider you have to import util package in your class,then your import statement is as look like below statement.

 import java.util.*;


here:
import   : Keyword in java
java.util : Name of  Package
*           : All content present in respective package.

Use the import keyword whenever the class in the particular package has to be used.


Application of Package :

  1. Avoid Naming complexity
  2. Hide the implementation details of classes.
  3. It allows us to grouping classes and interfaces into the same directory.

How to Create My Own Package

follow the next steps

  • Use the keyword package at the beginnning of your class.
  • Create Directory of that package Name
  • Compile the classes and copy the .class file into package directory. 
  • Run your program by using following command

 java NameOf Package.ClassName

Write a program to Create a User defined package


Listen friend ,here you are creating your own package.you have to follow next procedure for the same purpose.

//Simple Program

package myPackage;
class SampleOne
{
 public void run()
 {
  System.out.println("This is run method");
 }

}

//Save this program as SampleOne.java and create new java program for next program


package myPackage;
class SampleTwo extends SampleOne
{
 public void running()
 {
  System.out.println("This is running method");
 }
 public static void main(String[] args)
 {
  SampleTwo st=new SampleTwo();
  st.run();
  st.running();
  System.out.println("Hello World!");
 }
}

//Save this program as SampleTwo.java and follow next procedure

How to Compile and Run package program

  • Got to cmd.
  • In  cmd,Go to path upto Java\jdk\bin
 
  • Comile the first program :

                     javac SampleOne.java

  • copy SampleOne.class file from bin directory to package directory called myPackage
  • then compile Second program

                     javac SampleTwo.java

  • copy SampleTwo.class file from bin directory to package directory called myPackage
  • Run the program

                   java myPackage.SampleTwo

  • Output looks like as below

here is your package will create with name myPackage.
If you have any doubt or wants some more program then keep use comment line ,I will reply you as soon as possible.

ShareThis

Related Posts Plugin for WordPress, Blogger...