Monday 18 July 2011

Use of package in java programming for beginners


Packages are used in Java  to server the following:
prevent naming conflicts,
to control access,
to make searching/locating and usage of classes, interfaces, enumerations and annotations easier etc.
A Package can be defined as a grouping of related types(classes, interfaces, enumerations and annotations ) providing access protection and name space management.
Some of the existing packages in Java are::
  • java.lang - bundles the fundamental classes
  • java.io - classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces etc. It is a good practice to group related classes implemented by you so that a programmers can easily determine that the classes, interfaces, enumerations, annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classed.

Creating a package:

When creating a package, you should first choose a name for the package and put a package statement with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types will be put into an unnamed package.


Package statement defines a name space in which classes are stored.



/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cuboid;

/**
 *
 * @author ravikiran
 */
class box{
int length,breath,height;

double volume()
{
return (length*breath*height);
}
}



class boxs{
public void main(String[] args) {


box mybox=new box();
box yourbox=new box();

mybox.length=2;
mybox.breath=4;
mybox.height=10;

double vol;
vol=mybox.volume();
System.out.println("the volume of my box ="+vol);


yourbox.length=3;
yourbox.breath=7;
yourbox.height=5;


vol=yourbox.volume();
System.out.println("the volume of your box ="+vol);
}
}

1 comment:

  1. OUTPUT
    the volume of my box =80.0
    the volume of your box =105.0

    ReplyDelete