Professional Documents
Culture Documents
Package&Interface
Package&Interface
4.1 Packages
4.2 Creating and Using Packages
4.3 Access Modifiers
4.4 Interfaces
Packages
Packages are containers for classes that are used to keep the class name
space compartmentalized
Packaging is a mechanism for partitioning the class name space into more
manageable chunks
With out package the name of each class will be taken from the same
name space, unique name have to be used for each class to avoid name
collisions
Defining a Package
To create a package simply include a package command & package name
– general form of the package statement: package pkg-name;
– package statement defines a name space in which classes are stored
– Java uses file system directories to store packages
E.g. package MyPackage;
The .class files for any classes you declare to be part of MyPackage
must be stored in a directory called MyPackage
– Directory name must match the package name exactly
– More than one file can include the same package statement
If there is no package statement, the class names are put into the default
package, which has no name(<default package>)
Finding Packages and Classpath
How does the Java run-time system know where to look for packages that
you create?
– by default, the Java run-time system uses the current working directory
as its starting point
– Thus, if your package is in a subdirectory of the current directory, it
will be found
Consider the following package specification: package MyPack;
For a program to find MyPack:
the program must be executed from a directory immediately above
MyPack,
E.g. if package MyPack is in C:\MyPrograms\Java\MyPack
Then the class path to MyPack must be: C:\MyPrograms\Java
Multileveled Package