Java Reference
In-Depth Information
Note Chapter 2 's introduction to interfaces showed you how to declare constants
and method headers in the body of an interface. You can also declare interfaces
and classes in an interface's body. Because there are few good reasons to do this
( java.util.Map.Entry ,whichisdiscussedin Chapter5 , isoneexception),itis
probably best to avoid nesting interfaces and/or classes within interfaces.
Packages
Hierarchical structures organize items in terms of hierarchical relationships that exist
betweenthoseitems.Forexample,afilesystemmightcontaina taxes directorywith
multiple year subdirectories, where each subdirectory contains tax information pertin-
enttothatyear.Also,anenclosingclassmightcontainmultiplenestedclassesthatonly
make sense in the context of the enclosing class.
Hierarchicalstructuresalsohelptoavoidnameconflicts.Forexample,twofilescan-
nothavethesamenameinanonhierarchicalfilesystem(whichconsistsofasingledir-
ectory).Incontrast,ahierarchicalfilesystemletssame-namedfilesexistindifferentdir-
ectories.Similarly,twoenclosingclassescancontainsame-namednestedclasses.Name
conflicts do not exist because items are partitioned into different namespaces .
Java also supports the partitioning of top-level user-defined types into multiple
namespaces,tobetterorganizethesetypesandtoalsopreventnameconflicts.Javauses
packages to accomplish these tasks.
Thissectionintroducesyoutopackages.Afterdefiningthistermandexplainingwhy
packagenamesmustbeunique,thesectionpresentsthepackageandimportstatements.
ItnextexplainshowtheJVMsearchesforpackagesandtypes,andthenpresentsanex-
amplethatshowsyouhowtoworkwithpackages.Thissectionclosesbyshowingyou
how to encapsulate a package of classfiles into JAR files.
Tip Except forthemosttrivial oftop-level typesand(typically) thoseclasses that
serveasapplicationentrypoints,youshouldconsiderstoringyourtypes(especiallyif
they are reusable) in packages.
What Are Packages?
A package is a unique namespace that can contain a combination of top-level classes,
othertop-leveltypes,andsubpackages.Onlytypesthataredeclared public canbeac-
cessedfromoutsidethepackage.Furthermore,theconstants,constructors,methods,and
Search WWH ::




Custom Search