Packages

A package is a grouping of related types providing access protection and name space management. Note that types refers to classes, interfaces, enumerations, and annotation types. Enumerations and annotation types are special kinds of classes and interfaces, respectively, so types are often referred to in this lesson simply as classes and interfaces. In shorter words we say that a package is a collection of java files, and other Java packages.

Defining a Package

package NewPackage;

You can create a hierarchy of packages. To do so, simply separate each package name from the one above it by use of a period. The general form of a multileveled package statement is shown here:

package pkg1[.pkg2[.pkg3]];

Example of package is demonstrated as :

package package1;

public class PackageExample {
	public static void main(String[] args) {
		System.out.println("Package Example");
	}
}

In the above program package1 is a package or directory and executed or accessed as :
1. go to one up level from the directory in which your Java class is defined.
2. compile with : javac package1\PackageExample.java
3. run with : java package1.PackageExample

Access Specifiers

Classes and packages are both means of encapsulating and containing the name space and scope of variables and methods. Packages act as containers for classes and other subordinate packages. Classes act as containers for data and code. The class is Java’s smallest unit of abstraction. Because of the interplay between classes and packages, Java addresses four categories of visibility for class members:
• Subclasses in the same package
• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses
The three access specifiers, private, public, and protected, provide a variety of ways to produce the many levels of access required by these categories. Below table will provides full view of access specifiers with their access visibility.

Private No Modifier Protected Public
Same Class No Yes Yes Yes
Same Package No Yes Yes Yes
Different package subclass No No Yes Yes
different pacjage non-sobclass No No No Yes