Sunday, October 17, 2010

Java package tutorial for beginners

Packages in Java

,are containers for classes that are used to keep the class name space compartmentalized.For example,a package allows you to create a class named Xyz (any name given by you),which you can store in your own package with out any concern that it will collide with other packages.

Define Package:
                              Package is, a collection of .class files (know what is .class file),created by the user or predefined.

How to create a package:
                                      It is very simple, simply include package command as the first statement in a Java source file.Any classes declared in that file will belong to the specified package.
  
Package statement defines a name space in which classes are stored.If you omit the package statement, the class names are put into the default package,which has no name space.
Syntax:
             package pkg;
          Here 'pkg ' is the package name.
example:
               package Mypack;
      Mypack is package name.

sample programs:


1.create a package   
                              //Pack.java, this class will be included in Mypack1
                              package Mypack1;
                              Public class Pack

                              {
                              public int var=90;
                              public char c='e';
                               public void show()

                                 {
                                  System.out.println("These R "+var);
                                  }
                               }

//Here you don`t see main(), you can include main() also if you need to make it simple i did n`t include it.

Note:
         Save the program in the directory with same name as that of package name.
  i.e, Save Mypack1 package in the Mypack1 directory( folder). and save it with class name given,Pack

2.Now complie the program:
                         But don`t run,as there is no main(), the program will not run.Now after compiling .class file will be created, make sure that it will be in same directory(folder) where package is saved.
Work is accomplished!.Now you can include this package in any program as the specifier used is public you can also include in programs out of directory.

Now see How to import packages to any program.
.

No comments:

Post a Comment