Packages are used in Java in order to 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
You can define your own packages to bundle group of classes/interfaces, etc. It is a good practice to group related classes implemented by you so that a programmer 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 classes.
Let us look at an example that creates a package called animals. It is a good practice to use names of packages with lower case letters to avoid any conflicts with the names of classes, interfaces.
Below given package example contains interface named animals:
/* File name : Animal.java */ package animals; interface Animal { public void eat(); public void travel(); }
- 05:51
- 0 Comments