- Java provides a mechanism for partitioning the class name space into more manageable sections known as the package.
- Packages are container for classes that are used to keep the class name space compartmentalized.
- Packages are stored in a hierarchical manner and are explicitly imported into new class definition.
- The package provides both a naming and a visibility control mechanism.
- We can define classes inside a package that are not accessible by the code outside that package.
- We can also define class members that are accessible within the same package.
- It helps to hide implementation of the classes from the out side of the package.
Defining a Package
- To create a package, simply include a package keyword as the first statement in java source file.
- Any classes declared within that file will belong to the specified package.
- It defines a name space in which classes are stored.
- If no package is defined than class names are put into the default package, which has no name.
General form of package statement:
Package pkg_name;
- Where, pkg is the name of the package.
- package must be stored in to the directory and the directory name must match the package name exactly.
- More than one file can include the same package statement.
- Hierarchy of packages can also be created as follows:
package pkg1[ .pkg2 [.pkg3] ];
Example: package java.awt.image;
- This package must be stored in java/awt/image directory.
- package can not be renamed without renaming the directory in which the classes are stored.
package MyPack;
class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name=n;
bal=b;
}
void show()
{
if (bal>0)
System.out.println("Name is:" + name +":$" + bal);
}
}
class AccountBalance
{
public static void main(String args[])
{
Balance current[]=new Balance[3];
current[0]=new Balance("K.J.Fielding",123.23);
current[1]=new Balance("will tell",157.02);
current[2]=new Balance("Tom",-12.33);
for(int i=0;i<3;i++)
{
current[i].show();
}
}
}
Compilation of program:
C:\javaprogs\MyPack>javac AccountBalance.java
C:\javaprogs>java MyPack.AccountBalance
Access Protection
- Anything declared as public can be accessed from anywhere.
- private cannot be accessed from outside of its class.
- Default: when a member does not have an explicit access specification, it is visible to sub-classes as well as to other classes in the same package.
- Protected can be accessed outside the current package, but only to the subclass
- A class only has two possible access level: default and public. When a class is declared as public, it is accessible by any other code. If a class has default access, then it can only be accessed by other code within the same package.