Saturday, 10 August 2013

How TO Create Packages

Packages is the way of grouping a variety of classes or interfaces. Packages act as a container of classes.



  • The package statement should be the first line in the source file.
  • The classes contain in the package is of other program can be easily reused.
  • Two different packages can have classes with same name.



Two types of packages are used:

  •  Java API packages.
  • User defined packages.


Java API packages: The API packages are already define with in a package are called built in packages.For Ex:Java.lang, Java.util, Java.io.

User defined packages: Java also provide that the user can define their own package.

Now the question is how we can create and run user defined packages in java.In user defined packages we can also use built in packages.The procedure is:

Here is the program:


package mypackage;       //Package is the reserved syntax and mypackage  is the package name.

public class packs {
public void says(){
System.out.println("hello world");
}
}


  1. Now save this program in the package name folder.As the above example the package name is mypackage.
  2. Then save the program class name.java and then only compile the package.The packages are only compiled not run because they not have any main method.
  3.  Now create new file and import the package.



import mypack.*;    //This statement defines import the package and *  defines the all classes in the

                                    package  are  accessed 
class access{
public static void main(String args[]){
packs b=new packs();
b.says();

}
}

Now save this file class name.java outside from the package folder and then compile and run it.


Output of Program:

Packages


Like the Post? Do share with your Friends.

No comments:

Post a Comment

IconIconIconFollow Me on Pinterest

Blogger news

Blogroll

What's Hot