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
Creating a package:
When creating a package, you should 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.
The import Keyword:
If a class wants to use another class in the same package, the package name does not need to be used. Classes in the same package find each other without any special syntax.
The Directory Structure of Packages:
Two major results occur when a class is placed in a package:
- The name of the package becomes a part of the name of the class, as we just discussed in the previous section.
- The name of the package must match the directory structure where the corresponding bytecode resides.
No comments:
Post a Comment