29-11-2012, 04:20 PM
Packages
14498_Packages.ppt (Size: 532.5 KB / Downloads: 25)
Packages
Packages are Java’s way of grouping a variety of classes and/or interfaces together. The grouping is usually done according to functionality. Java Packages are classified into two types:
Java API Packages
User-defined Packages
Using System Packages
The packages are organized in a hierarchical structure.
There are two ways of accessing the classes stored in a package.
import packagename.class;
import packagename.*;
Creating Packages
To create a package we must first declare the name of the package using the package keyword followed by a package name. Then we define a class, just as we normally define a class.
package firstPackage;
public class FirstClass
{
body of class
}
Steps for creating packages
Declare the package at the beginning of a file using the form:package packagename;
Define the class that is to be put in the package and declare it public
Create a sub-directory under the directory where the main source files are stored
Store the listing as the classname .java file in the subdirectory created
Compile the file. This creates .class file in the subdirectory
Adding a class to a package
Define the class and make it public
Place the package statement before the class definition
Store this as .java file under the directory
Compile .java file. This will create a .class file and place it in the directory